【发布时间】:2016-03-06 20:29:48
【问题描述】:
这是我的第一个 stackoverflow 问题。
我正在尝试使用 dplyr 来处理和输出按我的数据集中的分类变量 (inj_length_cat3) 分组的数据摘要。实际上,我使用 mutate() 动态生成了这个变量(来自 inj_length)。我还想输出相同的数据摘要没有分组。我想出如何做到这一点的唯一方法是进行两次分析,一次有,一次没有分组,然后合并输出。呃。
我确信有比这更优雅的解决方案,它让我很烦恼。我想知道是否有人可以提供帮助。
谢谢!
library(dplyr)
df<-data.frame(year=sample(c(2005,2006),20,replace=T),inj_length=sample(1:10,20,replace=T),hiv_status=sample(0:1,20,replace=T))
tmp <- df %>%
mutate(inj_length_cat3 = cut(inj_length, breaks=c(0,3,100), labels = c('<3 years','>3 years')))%>%
group_by(year,inj_length_cat3)%>%
summarise(
r=sum(hiv_status,na.rm=T),
n=length(hiv_status),
p=prop.test(r,n)$estimate,
cilow=prop.test(r,n)$conf.int[1],
cihigh=prop.test(r,n)$conf.int[2]
) %>%
filter(inj_length_cat3%in%c('<3 years','>3 years'))
tmp_all <- df %>%
group_by(year)%>%
summarise(
r=sum(hiv_status,na.rm=T),
n=length(hiv_status),
p=prop.test(r,n)$estimate,
cilow=prop.test(r,n)$conf.int[1],
cihigh=prop.test(r,n)$conf.int[2]
)
tmp_all$inj_length_cat3=as.factor('All')
tmp<-merge(tmp_all,tmp,all=T)
【问题讨论】:
-
这里有一些关于在这里提出好问题的指导:stackoverflow.com/help/how-to-ask 关键是要提出一个minimal reproducible example
-
用最少的示例数据框和更好的标题进行了编辑。