从行名创建列并相应地排列数据(new data.frame(s))

时间:2018-03-10 16:25:57

标签: r

我的原始data.frame看起来像这样:

df1
      Group Variable      Text
        AB        a   Sentence1
        AB        b   Sentence2
        AB        c   Sentence3
        XY        d   Sentence4
        XY        e   Sentence5
        XY        f   Sentence6
        ZW        g   Sentence7
        ZW        h   Sentence8
        ZW        i   Sentence9

现在我需要像这样重新安排:

df2

     AB XY ZW     Text1     Text2     Text3
      a  d  g Sentence1 Sentence4 Sentence7
      b  e  h Sentence2 Sentence5 Sentence8
      c  f  i Sentence3 Sentence6 Sentence9

P.S:我的输出data.frame看起来像这样的原因是我稍后会连接每行的Text1-Text3列。但是我在R之外做。

非常感谢您的帮助!

df1&的代码DF2:

df1 <- data.frame(Group = c("AB", "AB", "AB", "XY", "XY", "XY", "ZW", "ZW", "ZW"), 
                  Variable = c("a", "b", "c", "d", "e", "f", "g", "h", "i"), 
                  Text = c("Sentence1", "Sentence2", "Sentence3", "Sentence4", "Sentence5", "Sentence6", "Sentence7", "Sentence8", "Sentence9"))

df2 <- data.frame(AB = c("a", "b", "c"), 
                  XY = c("d", "e", "f"), 
                  ZW = c("g", "h", "i"), 
                  Text1 = c("Sentence1", "Sentence2", "Sentence3"), 
                  Text2 = c("Sentence4", "Sentence5", "Sentence6"), 
                  Text3 = c("Sentence7", "Sentence8", "Sentence9"))

1 个答案:

答案 0 :(得分:1)

我们可以通过在dcast

中指定“变量”和“文字”,使用data.table中的value.var来执行此操作
library(data.table)
dcast(setDT(df1), rowid(Group) ~ Group, value.var = c('Variable', 'Text'))[, Group := NULL][]