首页 文章

使用列表中包含的一些但不是所有字符串的多个模式提取和组合多个子字符串并返回到R中的列表

提问于
浏览
1

我想找到一种优雅且易于操作的方式:

  • 从包含为列表元素的一些(但不是全部)字符串中提取多个子字符串(每个列表元素只包含一个长字符串)

  • 用这些多个子串替换相应的原始长字符串

  • 将每个列表元素中的子字符串折叠为1个字符串

  • 返回包含替换子字符串和未触及的长字符串的相同长度的列表 .

这个问题是我之前提出的问题的后续(虽然不同):replace strings of some list elements with substring . 注意,我不想在所有列表元素上运行正则表达式模式,只是那些正则表达式适用的元素 .

我知道最终结果可以由 str_replacesub 通过匹配要更改的整个字符串并返回捕获组捕获的文本来传递,如下所示:

library(stringr)
myList <- as.list(c("OneTwoThreeFourFive", "mnopqrstuvwxyz", "ghijklmnopqrs", "TwentyTwoFortyFourSixty"))
fileNames <- c("AB1997R.txt", "BG2000S.txt", "MN1999R.txt", "DC1997S.txt")
names(myList) <- fileNames
is1997 <- str_detect(names(myList), "1997")

regexp <- ".*(Two).*(Four).*"
myListNew2 <- myList
myListNew2[is1997] <- lapply(myList[is1997], function(i) str_replace(i, regexp, "\\1££\\2"))

## This does return what I want:
myListNew2
$AB1997R.txt
[1] "Two££Four"

$BG2000S.txt
[1] "mnopqrstuvwxyz"

$MN1999R.txt
[1] "ghijklmnopqrs"

$DC1997S.txt
[1] "Two££Four"

但我更愿意这样做而不必匹配整个原始文本(因为,例如,匹配非常长的文本所需的时间;多个正则表达式模式的复杂性和难以将它们编织在一起以便它们成功匹配整个字符串) . 我想使用单独的正则表达式模式来提取子字符串,然后用这些提取替换原始字符串 . 我想出了以下内容,它有效 . 但肯定有一种更简单,更好的方式! llply

patternA <- "Two"
patternB <- "Four"
x <- myList[is1997]
x2 <- unlist(x)
stringA <- str_extract (x2, patternA)
stringB <- str_extract (x2, patternB)
x3 <- mapply(FUN=c, stringA, stringB, SIMPLIFY=FALSE)
x4 <- lapply(x3, function(i) paste(i, collapse = "££"))
x5 <- relist(x4,x2)
myListNew1 <- replace(myList, is1997, x5)
myListNew1

$AB1997R.txt
[1] "Two££Four"

$BG2000S.txt
[1] "mnopqrstuvwxyz"

$MN1999R.txt
[1] "ghijklmnopqrs"

$DC1997S.txt
[1] "Two££Four"

1 回答

  • 2

    也许这样的事情,我已经扩展了你想要的模式,以展示它如何变得适应:

    library(stringr)
    patterns <- c("Two","Four","Three")
    hits <- lapply(myList[is1997], function(x) {
      out <- sapply(patterns, str_extract, string=x)
      paste(out[!is.na(out)],collapse="££")
    })
    myList[is1997] <- hits
    
    #[[1]]
    #[1] "Two££Four££Three"
    #
    #[[2]]
    #[1] "mnopqrstuvwxyz"
    #
    #[[3]]
    #[1] "ghijklmnopqrs"
    #
    #[[4]]
    #[1] "Two££Four"
    

相关问题