首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用tidyr创建两个带有tidyr的值列

使用tidyr创建两个带有tidyr的值列
EN

Stack Overflow用户
提问于 2015-05-11 18:46:13
回答 2查看 1.9K关注 0票数 4

我有一个像这样的数据框架(参见链接)。我想把下面产生的输出更进一步,把音调变量扩展到n和平均变量之间。看起来这个话题可能会影响到这一点,但我无法让它起作用:Is it possible to use spread on multiple columns in tidyr similar to dcast?

我希望最后一个表在一个列中有源变量,然后把tone和tone变量放在列中。因此,我希望列标题是"source“- "For - n”-“Avg n”表示-Avg“--”--“Avg”。这是为了出版,而不是为了进一步的计算,所以它是关于显示数据。在我看来,以这种方式显示数据似乎更直观。谢谢。

代码语言:javascript
复制
#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'))
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2015-05-11 19:12:48

我想你想要的是另一个集合,把计数和平均值作为单独的观测,下面的gather(type, val, -source, -tone)

代码语言:javascript
复制
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)

产量

代码语言:javascript
复制
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
票数 5
EN

Stack Overflow用户

发布于 2015-05-11 19:12:21

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

代码语言:javascript
复制
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'))
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/30175312

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档