R语言 的strsplit()函数
R编程语言中的 strsplit() 函数用于根据作为其参数的给定子串将指定字符向量的元素分割成子串。
语法: strsplit(x, split, fixed = FALSE, perl = FALSE, useBytes = FALSE)
参数: 该函数接受一些参数,如下图所示。
- x: 这是一个字符向量、数据文件或字符串,其每个元素将被分割。
- split: 该参数表示将指定的字符串X分割成所需的格式。
- fixed: 这个参数接受逻辑值。如果它的值为 “true”,它将准确地匹配和分割,否则使用正则表达式。
- perl: 这个参数接受逻辑值。
- useBytes: 这个参数接受逻辑值。如果它的值为 “true”,匹配是逐个字节进行的,而不是逐个字符进行的,带有标记编码的输入不会被转换。
返回值: 该函数返回一个新的分割字符串。
例1:使用strsplit()函数
这里我们要在字符串中应用这个函数。
# R program to illustrate
# strsplit() function
# Initializing a string
String <- ("GFG is a CS Portal.")
# Calling the strsplit() function over
# the above string to split the given input
# into a list of strings or values
strsplit(String, " ")
输出:
[[1]]
[1] "GFG" "is" "a" "CS" "Portal."
例2:在strsplit()函数中使用分隔符
分隔符只是一个字符或数值,用来分隔数据中的单词或文本。在下面的例子中,strsplit()函数与分隔符”//”一起使用,将由分隔符”//”分隔的单词分开。
# R program to illustrate
# strsplit() function
# Initializing a string
String <- ("GFG//is//a//CS//Portal.")
# Calling the strsplit() function over
# the above string to split the given
# input separated by "//"
# into a list of strings or values
strsplit(String, "//")
输出
[[1]]
[1] "GFG" "is" "a" "CS" "Portal."
例3:使用正则表达式和strsplit()函数
在下面的例子中,文本用正则表达式"[0-9]+"
分开,strsplit()函数被用来分割那些用正则表达式分开的文本。
# R program to illustrate
# strsplit() function
# Initializing a string
String <- ("GeeksforGeeks13is456a246Computer9Science10Portal.")
# Calling the strsplit() function over
# the above string to split the given
# input separated by the regular expression "[0-9]+"
# into a list of strings or values
strsplit(String, "[0-9]+")
输出
[[1]]
[1] "GeeksforGeeks" "is" "a" "Computer"
[5] "Science" "Portal."
例4:拆分字符串中的每个字符
在下面的例子中,在strsplit()函数的帮助下,输入字符串的每个字符都被拆分。
# R program to illustrate
# strsplit() function
# Initializing a string
String <- ("GFG is a CS Portal.")
# Calling the strsplit() function over
# the above string to split the given
# input into each characters as string
strsplit(String, "")
输出
[[1]]
[1] “G” “F” “G” ” ” “I” “S” ” ” “A” ” “C” “S” ” ” “P” “O” “R” “T” “A” “L” ” 。
例5:用这个函数分割日期
在下面的例子中,strsplit()函数被用来将指定的日期分割成日期、月份和年份等各个部分。
# Initializing some date values
Date_values <- c("20-08-2021", "12-07-2019",
"02-05-2020")
# Calling the strsplit() function over the above
# specified date values along with the split
# format of "-"
Result <- strsplit(Date_values, split = "-")
# Getting the split date
Result
# Getting the split date in the form of
# matrix of 3 column
matrix(unlist(Result), ncol=3, byrow=T)
输出
[[1]]
[1] "20" "08" "2021"
[[2]]
[1] "12" "07" "2019"
[[3]]
[1] "02" "05" "2020"
[,1] [,2] [,3]
[1,] "20" "08" "2021"
[2,] "12" "07" "2019"
[3,] "02" "05" "2020"