R strsplit有多个无序拆分参数?

时间:2012-05-24 13:45:51

标签: r split

给定一个字符串

test_1<-"abc def,ghi klm"
test_2<-"abc, def ghi klm"

我希望获得

"abc"
"def"
"ghi"

但是,使用strsplit时,必须知道字符串中拆分值的顺序,因为strsplit使用第一个值进行第一次拆分,第二次执行第二次拆卸...然后回收。

但这不是:

strsplit(test_1, c(",", " "))
strsplit(test_2, c(" ", ","))

strsplit(test_2, split=c("[:punct:]","[:space:]"))[[1]]

我希望在一个步骤中找到任何分裂值的地方拆分字符串。

4 个答案:

答案 0 :(得分:54)

实际上strsplit也使用grep模式。 (逗号是一个正则表达式字符,而空格不是;因此需要在模式参数中双重转义逗号。因此"\\s"的使用将更多地提高可读性而不是必要性):

> strsplit(test_1, "\\, |\\,| ")
[[1]]
[1] "abc" "def" "ghi" "klm"

> strsplit(test_2, "\\, |\\,| ")
[[1]]
[1] "abc" "def" "ghi" "klm"

不使用\\,\\,(注意SO未显示的额外空格),您将获得一些字符(0)值。如果我写的话可能会更清楚:

> strsplit(test_2, "\\,\\s|\\,|\\s")
[[1]]
[1] "abc" "def" "ghi" "klm"

@Fojtasek是如此正确:使用字符类通常会简化任务,因为它会创建一个隐含的逻辑OR:

> strsplit(test_2, "[, ]+")
[[1]]
[1] "abc" "def" "ghi" "klm"

> strsplit(test_1, "[, ]+")
[[1]]
[1] "abc" "def" "ghi" "klm"

答案 1 :(得分:6)

如果您不喜欢正则表达式,可以多次调用strsplit()

strsplits <- function(x, splits, ...)
{
    for (split in splits)
    {
        x <- unlist(strsplit(x, split, ...))
    }
    return(x[!x == ""]) # Remove empty values
}

strsplits(test_1, c(" ", ","))
# "abc" "def" "ghi" "klm"
strsplits(test_2, c(" ", ","))
# "abc" "def" "ghi" "klm"
已添加的示例

已更新

strsplits(test_1, c("[[:punct:]]","[[:space:]]"))
# "abc" "def" "ghi" "klm"
strsplits(test_2, c("[[:punct:]]","[[:space:]]"))
# "abc" "def" "ghi" "klm"

但是如果你打算使用正则表达式,你可以选择@DWin的方法:

strsplit(test_1, "[[:punct:][:space:]]+")[[1]]
# "abc" "def" "ghi" "klm"
strsplit(test_2, "[[:punct:][:space:]]+")[[1]]
# "abc" "def" "ghi" "klm"

答案 2 :(得分:5)

您可以使用strsplit(test_1, "\\W")

答案 3 :(得分:1)

 test_1<-"abc def,ghi klm"
 test_2<-"abc, def ghi klm"
 key_words <- c("abc","def","ghi")
 matches <- str_c(key_words, collapse ="|")
 str_extract_all(test_1, matches)
 str_extract_all(test_2, matches)