我有一个软件可以生成宽度有限的实验数据,这样一串数据点将被包装到最终 csv 中限制为 4 列宽的一系列行中,而不是每个变量一行(下面的 A 和 B)这是我需要的形式。(下面的示例 csv)
A,1,3,3,2
,5,6,7,8
,9,10,11,12
,13,1,15,6
,17,1,2,20
B,1,2,3,7
,7,6,7,8
,9,10,11,12
,13,15,15,16
,17,18,3,2
在实际数据中,这让我每天要处理大约 53,000 行,所以我想知道是否有一个函数可以让我解包或重新标注给定的数据子集(每个变量)成单行。在上面的示例中,变量 A 之后的数字将合并到一行中,同时保持顺序(即 1,3,3,2,5...),B 也是如此,依此类推。
根据要求,生成上述简化示例的 dput 输出..
structure(list(V1 = structure(c(2L, 1L, 1L, 1L, 1L, 3L), .Label = c("",
"A", "B"), class = "factor"), V2 = c(1L, 5L, 9L, 13L, 17L, 1L
), V3 = c(2L, 6L, 10L, 14L, 18L, 2L), V4 = c(3L, 7L, 11L, 15L,
19L, 3L), V5 = c(4L, 8L, 12L, 16L, 20L, 4L)), .Names = c("V1",
"V2", "V3", "V4", "V5"), row.names = c(NA, 6L), class = "data.frame")
最佳答案
您可以使用外部工具来预处理文件,
read.csv(pipe("sed -e :a -e '$!N;s/\\n,//;ta' -e 'P;D' file.txt"), head=FALSE)
本质上,file.txt
首先由 unix 工具 sed
处理,它执行搜索和替换并将新内容返回给 R。正则表达式我改编自 this page执行以下任务:
If a line begins with a comma, append it to the previous line
and replace the "," with nothing
编辑(eddi -- 注意:这在 Mac OS 上似乎不起作用) 下面是 sed
解析以下命令的方式:
read.csv(pipe("sed ':a; N; s/\\n,/,/; t a; P; D' file.txt"), head=FALSE)
:a # label (named "a") we're going to come back to
N # read in the next line into pattern space, together with the newline character
s/\n,/,/ # if there is a newline followed by comma, delete the newline
t a # go back to "a" and repeat until the above match fails (t stands for test)
P # print everything in pattern space up to and including last \n
D # delete everything in pattern space up to and including last \n
关于r - 将连续数据展开为 R 中的单行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18132118/