美文网首页
R语言 字符串切割

R语言 字符串切割

作者: 唐伯虎点蚊香7 | 来源:发表于2019-05-03 22:14 被阅读0次

    1. strsplit {base}

    语法:

    strsplit(x, split, fixed = FALSE, perl = FALSE, useBytes = FALSE)

    参数:x待切割的字符串;split分割符。
    备注:返回值为list。

    示例:
    strsplit("a.b.c", ".", fixed = TRUE)
    [[1]]
    [1] "a" "b" "c"
    

    2. str_split {stringr}

    语法:

    str_split(string, pattern, n = Inf, simplify = FALSE)
    str_split_fixed(string, pattern, n) ##与str_split参数simplify为TRUE效果一致

    参数:string待切割的字符串;pattern分割符;n切割为多少列;simplify如果为FALSE,返回值为字符串向量的list,如果为TRUE,返回值为字符串矩阵的list。

    示例:
    library("stringr")
    
    fruits <- c(
    +     "apples and oranges and pears and bananas",
    +     "pineapples and mangos and guavas"
    + )
    
    str_split(fruits, " and ")
    [[1]]
    [1] "apples"  "oranges" "pears"   "bananas"
    
    [[2]]
    [1] "pineapples" "mangos"     "guavas"    
    
    ## simplify的作用
    str_split(fruits, " and ", simplify = TRUE)
         [,1]         [,2]      [,3]     [,4]     
    [1,] "apples"     "oranges" "pears"  "bananas"
    [2,] "pineapples" "mangos"  "guavas" ""       
    ## n的作用
    str_split(fruits, " and ", n = 3)
    [[1]]
    [1] "apples"            "oranges"           "pears and bananas"
    
    [[2]]
    [1] "pineapples" "mangos"     "guavas"    
    
    str_split(fruits, " and ", n = 3, simplify = TRUE)
         [,1]         [,2]      [,3]               
    [1,] "apples"     "oranges" "pears and bananas"
    [2,] "pineapples" "mangos"  "guavas" 
    
    str_split_fixed(fruits, " and ", 3)  ##与str_split(fruits, " and ", n = 3, simplify = TRUE)效果一致
         [,1]         [,2]      [,3]               
    [1,] "apples"     "oranges" "pears and bananas"
    [2,] "pineapples" "mangos"  "guavas"  
    

    相关文章

      网友评论

          本文标题:R语言 字符串切割

          本文链接:https://www.haomeiwen.com/subject/imiznqtx.html