r - 将重复的列集收集到单个列中

标签 r data.table reshape reshape2 tidyr

此处已解决收集多组列的问题:Gather multiple sets of columns ,但就我而言,列不是唯一的。

我有以下数据:

input <- data.frame(
  id = 1:2, 
  question = c("a", "b"),
  points = 0,
  max_points = c(3, 5),
  question = c("c", "d"),
  points = c(0, 20),
  max_points = c(5, 20),
  check.names = F,
  stringsAsFactors = F
)
input
#>   id question points max_points question points max_points
#> 1  1        a      0          3        c      0          5
#> 2  2        b      0          5        d     20         20

第一列是一个id,然后我有很多重复的列(原始数据集有133列):

  1. 问题标识符
  2. 给分
  3. 最高分

我想以这种结构结束:

expected <- data.frame(
  id = c(1, 2, 1, 2),
  question = letters[1:4],
  points = c(0, 0, 0, 20),
  max_points = c(3, 5, 5, 20),
  stringsAsFactors = F
)
expected
#>   id question points max_points
#> 1  1        a      0          3
#> 2  2        b      0          5
#> 3  1        c      0          5
#> 4  2        d     20         20

我试过几种方法:

  • tidyr::gather(input, key, val, -id)
  • reshape2::melt(input, id.vars = "id")

两者都没有提供所需的输出。此外,如果列比此处显示的多,gather 将不再起作用,因为重复列太多。

作为解决方法,我试过这个:

# add numbers to make col headers "unique"
names(input) <- c("id", paste0(1:(length(names(input)) - 1), names(input)[-1]))

# gather, remove number, spread
input %>% 
  gather(key, val, -id) %>%
  mutate(key = stringr::str_replace_all(key, "[:digit:]", "")) %>%
  spread(key, val)

这给出了一个错误:Duplicate identifiers for rows (3, 9), (4, 10), (1, 7), (2, 8)

这里已经讨论过这个问题:Unexpected behavior with tidyr ,但我不知道为什么/如何添加另一个标识符。这很可能不是主要问题,因为我可能应该以不同的方式处理整个问题。

如何解决我的问题,最好是使用 tidyr 或 base?我不知道如何使用 data.table,但如果有一个简单的解决方案,我也会满足于此。

最佳答案

试试这个:

do.call(rbind,
        lapply(seq(2, ncol(input), 3), function(i){
          input[, c(1, i:(i + 2))]
              })
        )

#   id question points max_points
# 1  1        a      0          3
# 2  2        b      0          5
# 3  1        c      0          5
# 4  2        d     20         20

关于r - 将重复的列集收集到单个列中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38099689/

相关文章:

python - 为什么 3d 数组的打印结果与 python 中相同的心理可视化不同?

R:将行转为列,并使用 N/A 表示缺失值

r - 我想同时扩大范围和扩展,但遇到了问题

c++ - Armadillo 使用的随机数生成器是什么?

r - 计算许多 csv 文件按类型分割的行数 R

r - 如何使用 data.table 将表格应用于多个列?

r - 使用 `data.table` 包在 R 中使用键的子集数据

r - 无法找到加载了 dplyr 的函数 "%<>%"

r - 如何从 R 中的线性模型获得 1000 个预测?

r - dplyr::lead 或 data.table::shift 引用变量值而不是标量