【问题标题】:Loop through data frame to search for multiple patterns and report them循环遍历数据框以搜索多个模式并报告它们
【发布时间】:2017-08-13 23:04:38
【问题描述】:

我正在尝试创建一个循环来计算数据框行中的多个模式并报告新数据框中的出现次数。

这是我的输入:

input <- data.frame(V1 = LETTERS[1:4], 
             V2 = c("ABCDEF", "AAABBBCCA", "CCAABBCC", "ACCCCCCA"),
             stringsAsFactors = FALSE)

我要搜索的模式列表:

list<-c("ABC", "AA", "CC", "CCCC", "A")

预期输出:

structure(list(V1 = structure(1:4, .Label = c("A", "B", "C", 
"D"), class = "factor"), V2 = structure(c(2L, 1L, 4L, 3L), .Label = c("AAABBBCCA", 
"ABCDEF", "ACCCCCCA", "CCAABBCC"), class = "factor"), ABC = c(1L, 0L, 0L, 0L), AA = c(0L, 1L, 1L, 0L), CC = 0:3, CCCC = c(0L, 0L, 0L, 1L), A = c(1L, 4L, 2L, 1L), ABC_length = c(1L, 0L, 0L, 0L), AA_length = c(0L, 1L, 1L, 0L), CC_length = structure(1:4, .Label = c("0", "1", "1,1", "2"), class = "factor"), CCCC_length = c(0L, 0L, 0L, 1L), A_length = structure(c(1L, 4L, 3L, 2L), .Label = c("1", "1,1", "2", "3,1"), class = "factor")), .Names = c("V1", "V2",     "ABC", "AA", "CC", "CCCC", "A", "ABC_length", "AA_length", "CC_length",     "CCCC_length", "A_length"), class = "data.frame", row.names = c(NA, -4L))

一种解决方案可能是使用 str_count 或 str_locate_all,示例如下。 但实际上我想使用上述模式列表进行搜索。

library(stringr)
input$ABC <- str_count(input$ABC, "ABC")
input$ABC_length <- lapply(str_locate_all(input$ABC_length, "ABC"), function(x) {
  paste(x[, 2] - x[, 1] + 1, collapse = ",")
})

【问题讨论】:

  • 为了清楚起见,我的示例包括如何找到一个模式“ABC”的解决方案,但问题是关于搜索多个模式
  • 您没有找到“ABC”模式的解决方案,因为您指的是要创建的列。

标签: r regex find-occurrences


【解决方案1】:

您在正确的轨道上,但您指的是公式右侧的所需输出。而不是

input$ABC <- str_count(input$ABC, "ABC")

(这没有意义,因为input$ABC 尚未创建),试试

input$ABC = str_count(input$V2, "ABC")

input$ABC_length 的类似逻辑:您需要在等式右侧引用 input$V2,而不是 input$ABC_length

【讨论】:

  • 是的,这样我只会计算“ABC”,我可以对列表中的所有组合都这样做吗?
  • 逻辑是一样的:不要引用等式右边的输出列。
  • 是的,但是如何创建一个循环,将每个模式的数据输出到数据帧中
猜你喜欢
  • 2021-01-19
  • 1970-01-01
  • 2021-11-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多