English · PDF 242
使用 str_split() 将字符串拆分成多个片段。例如,我们可以将句子拆分成单词:
sentences %>% head(5) %>% str_split(" ") #> [[1]] #> [1] "The" "birch" "canoe" "slid" "on" "the" #> [7] "smooth" "planks." #> #> [[2]] #> [1] "Glue" "the" "sheet" "to" #> [5] "the" "dark" "blue" "background." #> #> [[3]] #> [1] "It's" "easy" "to" "tell" "the" "depth" "of" #> [8] "a" "well." #> #> [[4]] #> [1] "These" "days" "a" "chicken" "leg" "is" #> [7] "a" "rare" "dish." #> #> [[5]] #> [1] "Rice" "is" "often" "served" "in" "round" #> [7] "bowls."
因为每个元素可能包含不同数量的片段,所以该函数返回一个列表。如果你处理的是长度为 1 的向量,最简单的方法就是直接提取列表的第一个元素:
"a|b|c|d" %>% str_split("\|") %>% .[[1]] #> [1] "a" "b" "c" "d"
否则,与其他返回列表的 stringr 函数一样,你可以使用 simplify = TRUE 来返回一个矩阵: