【问题标题】:Using spread to create two value columns with tidyr使用 spread 用 tidyr 创建两个值列
【发布时间】:2015-07-22 09:48:19
【问题描述】:

我有一个看起来像这样的数据框(请参阅链接)。我想采用下面产生的输出,并通过将色调变量分布在 n 和平均变量上更进一步。似乎这个话题可能与此有关,但我无法让它发挥作用: Is it possible to use spread on multiple columns in tidyr similar to dcast?

我希望最终表将源变量放在一列中,然后将tone-n 和tone-avg 变量放在列中。所以我希望列标题是“源” - “For - n” - “Against - n” “For -Avg” - “Against - Avg”。这是为了发布,而不是为了进一步计算,所以它是关于呈现数据的。以这种方式呈现数据对我来说似乎更直观。谢谢。

#variable1
Politician.For<-sample(seq(0,4,1),50, replace=TRUE)
#variable2
Politician.Against<-sample(seq(0,4,1),50, replace=TRUE)
#Variable3
Activist.For<-sample(seq(0,4,1),50,replace=TRUE)
#variable4
Activist.Against<-sample(seq(0,4,1),50,replace=TRUE)
#dataframe
df<-data.frame(Politician.For, Politician.Against, Activist.For,Activist.Against)

#tidyr
df %>%
 #Gather all columns 
 gather(df) %>%
 #separate by the period character 
 #(default separation character is non-alpha numeric characterr) 
 separate(col=df, into=c('source', 'tone')) %>%
 #group by both source and tone  
 group_by(source,tone) %>%
 #summarise to create counts and average
 summarise(n=sum(value), avg=mean(value)) %>%
 #try to spread
 spread(tone, c('n', 'value'))

【问题讨论】:

  • 请显示所需的输出

标签: r tidyr spread


【解决方案1】:

我认为你想要的是另一个集合来打破计数并作为单独的观察表示,下面的gather(type, val, -source, -tone)

gather(df, who, value) %>%
    separate(who, into=c('source', 'tone')) %>%
    group_by(source, tone) %>%
    summarise(n=sum(value), avg=mean(value)) %>%
    gather(type, val, -source, -tone) %>%
    unite(stat, c(tone, type)) %>%
    spread(stat, val)

产量

Source: local data frame [2 x 5]

      source Against_avg Against_n For_avg For_n
1   Activist        1.82        91    1.84    92
2 Politician        1.94        97    1.70    85

【讨论】:

    【解决方案2】:

    使用data.table 语法(感谢@akrun):

    library(data.table)
    dcast(
      setDT(melt(df))[,c('source', 'tone'):=
          tstrsplit(variable, '[.]')
        ][,list(
          N  = sum(value),
          avg= mean(value))
        ,by=.(source, tone)],
      source~tone,
      value.var=c('N','avg'))
    

    【讨论】:

    • @akrun 好的,谢谢你的提示!如果dplyr 的计划不包括dcastmelt(因为它们起源于hadleyverse),这似乎有点奇怪(和限制)。
    • 可能 tidyr 是用来做某些事情的。我猜reshape2 (?reshape3) 的下一个版本会纠正这些问题。
    • 我更喜欢melt(setDT(df)),(但有一个友好的警告信息可能会吓到人们),这样我们就不需要加载reshape2
    • @akrun 随意编辑;我对这些东西还不太了解
    • @Arun 随意编辑,删除我的 1.9.4 kludge 或其他任何内容。
    猜你喜欢
    • 1970-01-01
    • 2019-12-31
    • 2019-05-19
    • 2016-03-07
    • 2018-08-19
    • 1970-01-01
    • 1970-01-01
    • 2016-10-05
    • 1970-01-01
    相关资源
    最近更新 更多