【发布时间】: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