【问题标题】:Gather groups of columns [duplicate]收集列组[重复]
【发布时间】:2017-04-07 14:13:36
【问题描述】:

我有来自在线调查的数据,受访者回答了一系列 5 个问题。 我正在处理的数据如下所示:

    P1 P2 P3 P4 P5  P1 P2 P3 P4 P5  P1 P2 P3 P4 P5
    1  2  3  4  5   1  2  3  4  5   1  2  3  4  5
    6  7  8  9  10  6  7  8  9  10  6  7  8  9  10

想要的输出是:

     P1 P2 P3 P4 P5  
     1  2  3  4  5
     6  7  8  9  10
     1  2  3  4  5
     6  7  8  9  10
     1  2  3  4  5
     6  7  8  9  10

我一直在尝试使用 tidyr 库来解决这个问题,但我不明白如何应用它。 对此提出一些建议会很有帮助。

【问题讨论】:

  • 你能dput你的数据给我们吗?您只是想将每组 5 列堆叠在一起吗?
  • 我想这也可以:data.frame(split(unlist(indf, use.names = FALSE), rep(names(indf), each = nrow(indf))))....

标签: r tidyr


【解决方案1】:

其中一种解决方案可以是:

require(foreach)
require(dplyr)
require(magrittr)    

foreach(
  unique_name = unique(colnames(df)),
  .combine = 'bind_cols'
) %do% {

  df[grep(unique_name), colnames(df)] %>%
    unlist() %>%
    as.data.frame() %>%
    set_colnames(., unique_names)

}

【讨论】:

  • 您的代码中多了一个)
猜你喜欢
  • 2016-11-23
  • 1970-01-01
  • 1970-01-01
  • 2016-08-14
  • 1970-01-01
  • 2016-11-01
  • 2013-09-05
  • 2021-09-25
  • 1970-01-01
相关资源
最近更新 更多