我有一个看起来像这样的数据框(请参阅链接)。我想采用下面产生的输出,并通过将色调变量分布在 n 和平均变量上更进一步。似乎这个主题可能与此有关,但我无法让它发挥作用: 是否可以在类似于 dcast 的 tidyr 的多个列上使用传播?
我希望最终表将源变量放在一列中,然后将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'))