【问题标题】:R (dplyr, tidyr): combine/aggregate related columns [duplicate]R(dplyr,tidyr):组合/聚合相关列[重复]
【发布时间】:2017-03-21 13:59:59
【问题描述】:

如何按以下方式组合数据框的列?

data <- data.frame(user.A = c(2,4,6), 
               user.B = c(11,13,15), 
               other.A = c(102,104,106), 
               other.B = c(201,103,105), 
               id = c('001', '004', '006'))
data
  user.A user.B other.A other.B  id
1      2     11     102     201 001
2      4     13     104     103 004
3      6     15     106     105 006

# Desired output.
  user other  id
1    2   102 001
2   11   201 001
3    4   104 004
4   13   103 004
5    6   106 006
6   15   105 006

我相信这可以通过dyplrtidyr 完成。 dplyr 中的 bind_rows 函数执行类似的操作,但不会创建所需的输出。

【问题讨论】:

    标签: r dplyr tidyr


    【解决方案1】:

    您可以使用reshape 函数的变体,如下所示:

    new_data <- reshape(data, varying = 1:4, direction = "long")
    

    varying 参数用于指定要旋转的列。

    【讨论】:

    • 对于所有的仇恨基地reshape(),它有时真的很聪明。
    【解决方案2】:

    使用 meltdata.table 更容易,因为它可以使用多个 measure patterns

    library(data.table)
    melt(setDT(data), measure = patterns("^user", "^other"),
          value.name = c("user", "other"))[, variable := NULL][]
    #   id user other
    #1: 001    2   102
    #2: 004    4   104
    #3: 006    6   106
    #4: 001   11   201
    #5: 004   13   103
    #6: 006   15   105
    

    作为'user','other'列是numeric,我们也可以使用gather/spread from tidyr

    library(dplyr)
    library(tidyr)
    gather(data, var, val, -id) %>%
            separate(var, into = c("var1", "var2")) %>%
            spread(var1, val) %>% 
            select(-var2)
    #  id other user
    #1 001   102    2
    #2 001   201   11
    #3 004   104    4
    #4 004   103   13
    #5 006   106    6
    #6 006   105   15
    

    【讨论】:

      猜你喜欢
      • 2017-06-12
      • 1970-01-01
      • 2018-07-30
      • 1970-01-01
      • 2018-10-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多