在 R 中按分隔符拆分字符串

Jinku Hu 2023年1月30日 2021年7月16日
  1. 在 R 中使用 strsplit 按分隔符拆分字符串
  2. 在 R 中使用 str_split 按分隔符拆分字符串
在 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_splitstringr 包的一部分。它的工作方式几乎与 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" ""
Author: Jinku Hu
Jinku Hu avatar Jinku Hu avatar

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

相关文章 - R String