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"
网友评论