我有一个看起来像这样的数据框(见链接).我想获取下面产生的输出,并通过在n和平均变量上扩展色调变量更进一步.似乎这个主题可能会对此产生影响,但我无法使其工作: 是否可以在tidyr中的多个列上使用传播类似于dcast?
我希望最终表将源变量放在一列中,然后将tone-n和tone-avg变量放在列中.所以我希望列标题为"source" - "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'))
Run Code Online (Sandbox Code Playgroud)
我认为你想要的是另一个聚集来突破计数并且意味着单独的观察,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)
Run Code Online (Sandbox Code Playgroud)
产量
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
Run Code Online (Sandbox Code Playgroud)