假设我们有这些数据:
dat<-data.frame(id=c(1,1,2,2,3,4,4,5,6,6),Rx=c(1,2,1,2,1,1,1,2,2,2))
id Rx
1 1 1
2 1 2
3 2 1
4 2 2
5 3 1
6 4 1
7 4 1
8 5 2
9 6 2
10 6 2其中Id是主题id,Rx是他们所接受的治疗。因此,有重复的观察和治疗可能是一致的,也可能不是一致的每一个主题。
我想总结一下有多少人只收到了Rx 1,只收到了Rx 2,有多少人收到了Rx 1和2。
我更喜欢dplyr解决方案,但data.table和base R也可以。我想:
dat %>%
group_by(id,Rx) %>%
unique() %>%
...something最终的结果应该是:
Rx Count
1 2
2 2
Both 2谢谢!
发布于 2015-02-04 16:51:52
这是另一个广义解
library(dplyr)
dat %>%
group_by(id) %>%
summarise(indx = toString(sort(unique(Rx)))) %>%
ungroup() %>%
count(indx)
# Source: local data table [3 x 2]
#
# indx n
# 1 1, 2 2
# 2 1 2
# 3 2 2对于data.table,类似的
library(data.table)
setDT(dat)[, .(indx = toString(sort(unique(Rx)))), id][ , .N, indx]发布于 2015-02-04 16:37:33
这个解决方案将而不是很好地推广到2种以上的治疗:
library(dplyr)
dat %>%
distinct(id, Rx) %>%
group_by(id) %>%
mutate(
trt1 = setequal(1, Rx), # change due to comment from @Marat Talipov
trt2 = setequal(2, Rx),
both = setequal(1:2, Rx)
) %>%
ungroup() %>%
distinct(id) %>%
summarise_each(funs(sum), trt1:both)该解决方案更短,并可概括为一种以上的治疗:
library(stringr)
dat %>%
group_by(id) %>%
mutate(
rx_list = str_c(sort(unique(Rx)), collapse = ",")
) %>%
distinct(id) %>%
count(rx_list)发布于 2015-02-04 16:52:40
不完全是您所指示的输出,但它是基R、一行和一般的:
table(do.call(function(...) paste(...,sep="_"),as.data.frame(table(dat)>0)))
#FALSE_TRUE TRUE_FALSE TRUE_TRUE
2 2 2如果治疗超过两个,你已经指出了所有可能的组合。
https://stackoverflow.com/questions/28326264
复制相似问题