在 R 中按分隔符拆分字串
本文將討論如何在 R 中通過分隔符分割字串。
在 R 中使用 strsplit
按分隔符拆分字串
strsplit
隨 R 基礎庫一起提供,應該可以在大多數安裝中使用而無需額外的包。strsplit
通過給定的分隔符將字元向量拆分為子字串,該分隔符也提供了一個字元向量。該函式的第一個引數是要拆分的字元向量。在這種情況下,我們指定空格字元來分隔給定句子中的每個單詞。請注意,輸出是作為字元向量列表給出的。
library(dplyr)
library(stringr)
str <- "Lorem Ipsum is simply dummied text of the printing and typesetting industry."
strsplit(str, " ")
輸出:
> strsplit(str, " ")
[[1]]
[1] "Lorem" "Ipsum" "is" "simply" "dummied" "text"
[7] "of" "the" "printing" "and" "typesetting" "industry."
在 R 中使用 str_split
按分隔符拆分字串
或者,str_split
函式也可用於按分隔符拆分字串。str_split
是 stringr
包的一部分。它的工作方式幾乎與 strsplit
相同,除了 str_split
還採用正規表示式作為模式。在下面的例子中,我們只傳遞固定字串進行匹配。請注意,該函式可以選擇採用第三個引數,該參數列示要返回的子字串的數量。
library(dplyr)
library(stringr)
str <- "Lorem Ipsum is simply dummied text of the printing and typesetting industry."
str_split(str, " ")
輸出:
> str_split(str, " ")
[[1]]
[1] "Lorem" "Ipsum" "is" "simply" "dummied" "text"
[7] "of" "the" "printing" "and" "typesetting" "industry."
str_split
函式中的另一個可選引數是 simplify
,它排在第四位。預設情況下,此引數的值為 FALSE
,這會強制函式將子字串作為字元向量列表返回。如果我們將 TRUE
分配給給定的引數,str_split
將返回一個字元矩陣。
library(dplyr)
library(stringr)
fruits <- c(
"apples and oranges and pears and bananas",
"pineapples and mangos and raspberries"
)
str_split(fruits, " and ")
str_split(fruits, " and ", simplify = TRUE)
輸出:
> str_split(fruits, " and ")
[[1]]
[1] "apples" "oranges" "pears" "bananas"
[[2]]
[1] "pineapples" "mangos" "raspberries"
> str_split(fruits, " and ", simplify = TRUE)
[,1] [,2] [,3] [,4]
[1,] "apples" "oranges" "pears" "bananas"
[2,] "pineapples" "mangos" "raspberries" ""
Founder of DelftStack.com. Jinku has worked in the robotics and automotive industries for over 8 years. He sharpened his coding skills when he needed to do the automatic testing, data collection from remote servers and report creation from the endurance test. He is from an electrical/electronics engineering background but has expanded his interest to embedded electronics, embedded programming and front-/back-end programming.
LinkedIn