首页 > 解决方案 > 通过 grep 匹配后在列表中组合向量

问题描述

我有一个包含 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 匹配。

标签: rvector

解决方案


在不知道您的数据的情况下。

你可以1)提取你的字符串,2)寻找这样的连续ID

library(stringr)
xx <- unique(x)
# loop over the xx vector and extract the ids
ids <- sapply(xx, function(s) str_extract(s, "\(id: [0-9]+\)"))

# filter for successive values
suc_ids <- ids[ids == lag(ids)]

推荐阅读