将数据重塑为宽格式

时间:2017-03-01 15:15:17

标签: r reshape

我希望将数据设置为特定格式,但不知道如何使用reshape()完成。

我的数据如下:

df<-data.frame(Cues=c("A","B","C","A","B","C"), 
               Targets=rep(1:3,2), 
               Rater=rep(1:2, each=3), 
               Rating=c(1,3,5,2,4,6))

我想得到它:

df2<-data.frame(Targets=rep(1:3,2), 
                Cues=c("A","B","C","A","B","C"), 
                Rater_1= c(1,2), 
                Rater_2=c(3,5), 
                Rater_3C=c(5,6))

我尽力使用论坛reshape(),并没有真正进一步发展。你能帮助我吗?

提前和最好的谢谢, 约什

1 个答案:

答案 0 :(得分:0)

注意: df data.frame设置中没有3C评估者,所以这个答案忽略了这个问题。

考虑到这一点,使用来自reshape2模块的dcast函数,从长格式数据转换为宽格式数据的一种方法是:

library(reshape2)
df2 <- dcast(df, Targets + Cues ~ Rater, value.var = "Rating")
names(df2)[names(df2) == "1"] <- "Rater_1"
names(df2)[names(df2) == "2"] <- "Rater_2"

df2
  Targets Cues Rater_1 Rater_2
1       1    A       1       2
2       2    B       3       4
3       3    C       5       6

此外,tidyr模块非常适合进行此类转换。

相关问题