【发布时间】:2021-03-01 15:39:17
【问题描述】:
我有一个包含 1000 个较小向量的列表/向量(“x”),每个向量 1 行。这些子向量包括字符串和数字。其中一行包括嵌入在字符串中的“id: XXXX”变量。如果我只考虑前 2 个向量(即 x[[i]] 和 x[[i+1]]),我可以使用 R 中的以下代码来组合列表中的连续向量。
first_vec<-c("Page 1 of 1000", "Report of vectors within a list", "id: 1234 height: 164 cms", "health: good")
second_vec<-c("Page 2 of 1000", "Report of vectors within a list", "id: 1235 height: 180 cms", "health: moderate")
third_vec<-c("Page 3 of 1000", "Report of vectors within a list", "id: 1235 weight: 200 pounds", "health: moderate")
x<-list(first_vec, second_vec, third_vec)
X <- for (i in i:unique(length(x))) {
t1 <- unlist(stringr::str_extract_all(x[[i]][!is.na(sample)], "(id: [0-9]+)"))
t2 <- unlist(stringr::str_extract_all(x[[i + 1]][!is.na(sample)], "(id: [0-9]+)"))
if (t1 == t2) {
c(x[[i]], x[[i + 1]])
}
}
想要的结果是:
x<-list(first_vec, c(second_vec, third_vec)
当我只有两个子向量时,这对我有用。但是,我有一个包含 1000 个向量的列表。如何在列表 x 中的所有向量中循环上面的代码?
目前我收到以下错误消息:
is.na(sample) 中的警告:
is.na() applied to non-(list or vector) of type 'closure'
Error in x[[i + 1]] : subscript out of bounds
我将包含一个我应用代码的典型输入文件的示例。在下面的示例中,我想合并第 2 页和第 3 页,因为 id 匹配。
【问题讨论】:
-
edit 标记语言,最好重新格式化代码以提高可读性,即在 3 个反引号组之间正确缩进。
-
另外,您可能需要添加一些数据以使其可重现。
-
你的代码没有玩具数据有什么用?请考虑how-to-make-a-great-r-reproducible-example
-
请使用
dput(x[1:3])或类似名称 -
抱歉,我无法通过 dput 分享,因为我遇到了阻碍我的保密问题。