【问题标题】:How to analyse a data set both grouped by and ungrouped in one analysis using dplyr如何使用 dplyr 在一次分析中分析分组和未分组的数据集
【发布时间】: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)

【问题讨论】:

标签: r group-by dplyr


【解决方案1】:

我不确定您是否认为这更优雅,但如果您首先创建一个包含所有数据的数据框两次,您可以获得一个可行的解决方案:一次是为了获取子组,一次是为了获取整体摘要:

df1 <- rbind(df,df)
df1$inj_length_cat3 <- cut(df$inj_length, breaks=c(0,3,100,Inf),
                           labels = c('<3 years','>3 years','All'))
df1$inj_length_cat3[-(1:nrow(df))] <- "All"

现在您只需要在没有mutate() 的情况下运行您的第一个分析:

tmp <- df1  %>% 
  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','All'))

【讨论】:

  • 太好了,如果此答案对您有用,您可以标记复选标记并投票(向上箭头)。
  • 我做到了——显然我需要更多的声望点!如果您可以在不必复制数据的情况下完成整个事情会更好(这会减慢分析速度,尤其是如果数据集很大)。
猜你喜欢
  • 2015-02-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-07
  • 1970-01-01
  • 2018-07-01
  • 2017-10-21
相关资源
最近更新 更多