问题描述
我正在做一些用户研究,每个人都以不同的顺序获得零件。数据看起来有点像这样。当前正在将所有内容导入数据表:
Question 3
1 6
2 9
Question 1
1 2
3 5
Question 2
2 5
1 2
我现在有多个 CSV 文件,每个“问题”行的顺序不同。 我可以搜索“问题”行,将它们与每个“问题”之间的所有内容分组并按顺序排列吗?之间会有多条线,我们不知道到底有多少条线。 所以它看起来像这样
Question 1
1 2
3 5
Question 2
2 5
1 2
Question 3
1 6
2 9
解决方法
解析文件是您的第一步,从那里订购应该直接使用 order
或 dplyr::arrange
。
txt <- readLines("quux.txt")
txt
# [1] "Question 3" "1 6" "2 9" "Question 1" "1 2" "3 5" "Question 2" "2 5" "1 2"
lst_of_frames <- lapply(
split(txt,cumsum(grepl("^Question",txt))),function(z) {
out <- read.table(header = FALSE,text = z[-1])
cbind(question = z[1],out)
})
lst_of_frames
# $`1`
# question V1 V2
# 1 Question 3 1 6
# 2 Question 3 2 9
# $`2`
# question V1 V2
# 1 Question 1 1 2
# 2 Question 1 3 5
# $`3`
# question V1 V2
# 1 Question 2 2 5
# 2 Question 2 1 2
我们现在有一个包含多个框架的列表。如果您希望将它们组合在一起,则存在多个选项:
results <- do.call(rbind,lst_of_frames)
results
# question V1 V2
# 1.1 Question 3 1 6
# 1.2 Question 3 2 9
# 2.1 Question 1 1 2
# 2.2 Question 1 3 5
# 3.1 Question 2 2 5
# 3.2 Question 2 1 2
dplyr::bind_rows(lst_of_frames) # similar results
data.table::rbindlist(lst_of_frames) # similar results
我将使用第一个的结果,然后使用
results[order(results$question,results$V1),]
# question V1 V2
# 2.1 Question 1 1 2
# 2.2 Question 1 3 5
# 3.2 Question 2 1 2
# 3.1 Question 2 2 5
# 1.1 Question 3 1 6
# 1.2 Question 3 2 9
dplyr::arrange(results,question,V1) # similar results
注意:这对每个问题中的列数很敏感。如果列数不同...
Question 3
1 6
2 9
Question 1
1 2 10
3 5 11
Question 2
2 5
1 2
然后你有一些选择。
-
保持广泛。简单的基础 R
do.call(rbind,...)
不再那么容易工作:do.call(rbind,lst_of_frames) # Error in rbind(deparse.level,...) : # numbers of columns of arguments do not match
但其他的工作正常:
dplyr::bind_rows(lst_of_frames) # question V1 V2 V3 # 1 Question 3 1 6 NA # 2 Question 3 2 9 NA # 3 Question 1 1 2 10 # 4 Question 1 3 5 11 # 5 Question 2 2 5 NA # 6 Question 2 1 2 NA data.table::rbindlist(lst_of_frames,fill = TRUE) # similar results
-
转向多头。(这是一个“宽对长”的数据讨论。)
dplyr::bind_rows(lapply(lst_of_frames,function(z) tidyr::pivot_longer(z,-question))) # # A tibble: 14 x 3 # question name value # <chr> <chr> <int> # 1 Question 3 V1 1 # 2 Question 3 V2 6 # 3 Question 3 V1 2 # 4 Question 3 V2 9 # 5 Question 1 V1 1 # 6 Question 1 V2 2 # 7 Question 1 V3 10 # 8 Question 1 V1 3 # 9 Question 1 V2 5 # 10 Question 1 V3 11 # 11 Question 2 V1 2 # 12 Question 2 V2 5 # 13 Question 2 V1 1 # 14 Question 2 V2 2 # similar results library(data.table) rbindlist(lapply(lst_of_frames,function(z) melt(as.data.table(z),id = "question")))
这种方法在其他领域有几个优点(例如,
ggplot2
、整洁的数据管理、易于总结等)。