【问题标题】:Combine vectors within a list after matching by grep通过 grep 匹配后在列表中组合向量
【发布时间】: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 分享,因为我遇到了阻碍我的保密问题。

标签: r vector


【解决方案1】:

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

您可以 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)]

【讨论】:

  • 谢谢。这非常适合提取匹配的 id
  • 如果您发现答案解决了您的问题,请考虑接受它作为答案!
  • 谢谢。我们有一些有用的回复,但本身没有确切的解决方案
【解决方案2】:

这是我对您的问题的理解和解决方案:您有一个单字符串向量列表,并且想要连接那些与模式匹配的子字符串。如果这是正确的,那么这应该可以工作:

数据:

a <- "id: 20"
b <- "something id: 333some more"
c <- "some other stuff without id"
d <- "some stuff id: 346999 and more stuff"
x <- list(a,b,c,d)

unlist(stringr::str_extract(x, "id: [0-9]+"))
[1] "id: 20"     "id: 333"    NA           "id: 346999"

或(也许):

paste0(unlist(stringr::str_extract(x, "id: [0-9]+")), collapse = ", ")
"id: 20, id: 333, NA, id: 346999"

根据 OP 的更新数据:

paste0(unlist(stringr::str_extract_all(x, "Page \\d+")), " ", unlist(stringr::str_extract_all(x, "id: [0-9]+")), collapse = ", ")
[1] "Page 1 id: 1234, Page 2 id: 1235, Page 3 id: 1235"

【讨论】:

  • 太棒了,谢谢。我可以以某种方式编辑上面的 paste0 命令,使“id”变量周围的剩余字符串保持不变吗?这意味着我的示例中的 x[[1]] 将是第 1 页,而 x[[i+1]] 将是第 2 页和第 3 页的组合。非常感谢
  • 您的数据的真正结构是怎样的?要我回答这个问题,您必须发布您的数据的 sn-p;尝试使用dput(head())
  • 抱歉,我无法通过 dput 分享,因为我遇到了阻碍我的保密问题。
  • 那你就编出一些和你相似的数据吧!
  • 已编辑答案。这是你需要的?
猜你喜欢
  • 1970-01-01
  • 2014-02-08
  • 2021-08-26
  • 1970-01-01
  • 1970-01-01
  • 2014-02-16
  • 2016-02-24
  • 1970-01-01
  • 2014-07-19
相关资源
最近更新 更多