【问题标题】:Make columns from row names and arrange data accordingly (new data.frame(s))从行名中创建列并相应地排列数据(新的 data.frame(s))
【发布时间】:2018-03-11 00:40:46
【问题描述】:

我的原始 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"))

【问题讨论】:

    标签: r


    【解决方案1】:

    我们可以通过在value.var 中指定“变量”和“文本”来使用data.table 中的dcast 来完成此操作

    library(data.table)
    dcast(setDT(df1), rowid(Group) ~ Group, value.var = c('Variable', 'Text'))[, Group := NULL][]
    

    【讨论】:

      猜你喜欢
      • 2019-08-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-11
      • 1970-01-01
      • 2015-03-11
      • 1970-01-01
      相关资源
      最近更新 更多