此处已解决收集多组列的问题: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列):
- 问题标识符
- 给分
- 最高分
我想以这种结构结束:
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/