id = sample.int(50,1000, replace = TRUE)
years <- c("2010", "2011", "2013", "2014", "2015")
year<- sample(years, 1000, prob=c(0.2,0.2,0.2,0.2, 0.2), replace = TRUE)
my_data = data.frame(id, year)
my_data <- my_data[order(id),]
例如,患者#1在2010年两次就诊,2011年一次,2012年没有一次...患者#2在2010年没有go 过医院,2011年5次,2012年3次,等等.
对于这个数据集,我想找出每个"年"组合出现的次数(不包括重复的次数).例如,由于有5个可能的年份,因此将有2^5=32个可能的组合:
# sample output of the final result
combinations frequency
2010 11
2011 9
2012 5
2013 1
2014 19
2015 11
2011,2012 9
2011, 2012, 2013 5
2013, 2015 1
2010,2011,2012,2013,2014,2015 19
这相当于发现:
- 2010年才有多少患者就诊?
- 2010年和2013年有多少患者就诊?
- 等
我试图找到一种不同的方法:
# Method 1: Did not work
library(data.table)
final = setDT(my_data)[,list(Count=.N) ,names(my_data)]
# Method 2: Did not work
final = = aggregate(.~year,rev(aggregate(.~id,my_data,paste0,collapse = ",")),length)
# Method 3: Not sure if this is correct? There are 50 rows (instead of 32) and all frequency counts are 1?
library(dplyr)
library(stringr)
df = my_data %>%
group_by(id) %>%
summarise(years = str_c(year, collapse=",")) %>%
count(years)
有人能告诉我怎么解决这个问题吗?