将字符向量分割成个别字符?(与paste或stringr::str_c相反)

siv3szwd  于 2022-12-05  发布在  其他
关注(0)|答案(4)|浏览(115)

这是R中一个非常基本的问题,但答案并不明确。
如何将一个字符向量拆分成它的单个字符,即paste(..., sep='')stringr::str_c()的相反字符?
任何比这更不笨重的东西:

sapply(1:26, function(i) { substr("ABCDEFGHIJKLMNOPQRSTUVWXYZ",i,i) } )
"A" "B" "C" "D" "E" "F" "G" "H" "I" "J" "K" "L" "M" "N" "O" "P" "Q" "R" "S" "T" "U" "V" "W" "X" "Y" "Z"

是否可以用其他方法来实现,例如,使用strsplit()stringr::*或其他方法?

jobtbby3

jobtbby31#

strsplit返回一个列表,因此可以使用unlist将字符串强制转换为单个字符向量,或者使用列表索引[[1]]访问第一个元素。

x <- paste(LETTERS, collapse = "")

unlist(strsplit(x, split = ""))
# [1] "A" "B" "C" "D" "E" "F" "G" "H" "I" "J" "K" "L" "M" "N" "O" "P" "Q" "R" "S"
#[20] "T" "U" "V" "W" "X" "Y" "Z"

OR(请注意,实际上不需要命名split参数)

strsplit(x, "")[[1]]
# [1] "A" "B" "C" "D" "E" "F" "G" "H" "I" "J" "K" "L" "M" "N" "O" "P" "Q" "R" "S"
#[20] "T" "U" "V" "W" "X" "Y" "Z"

您也可以在NULLcharacter(0)上分割,以取得相同的结果。

db2dz4w8

db2dz4w82#

stringr中的str_extract_all()提供了一种很好的方法来执行此操作:

str_extract_all("ABCDEFGHIJKLMNOPQRSTUVWXYZ", boundary("character"))

[[1]]
 [1] "A" "B" "C" "D" "E" "F" "G" "H" "I" "J" "K" "L" "M" "N" "O" "P" "Q" "R" "S" "T" "U"
[22] "V" "W" "X" "Y" "Z"
eanckbw9

eanckbw93#

由于stringr 1.5.0,您可以使用str_split_1str_split的一个版本,用于单个字符串:

library(stringr)
x <- paste(LETTERS, collapse = "")
str_split_1(x, "")
# [1] "A" "B" "C" "D" "E" "F" "G" "H" "I" "J" "K" "L" "M" "N" "O" "P" "Q" "R" "S"
#[20] "T" "U" "V" "W" "X" "Y" "Z"
kxeu7u2r

kxeu7u2r4#

This is rendered stepwise for clarity; in practice, a function would be created.
To find the number of times any character is repeated in sequence

the_string <- "BaaaaaaH"
# split string into characters
the_runs <- strsplit(the_string, "")[[1]]
# find runs
result <- rle(the_runs)
# find values that are repeated
result$values[which(result$lengths > 1)]
#> [1] "a"
# retest with more runs
the_string <- "BaabbccH"
# split string into characters
the_runs <- strsplit(the_string, "")[[1]]
# find runs
result <- rle(the_runs)
# find values that are repeated
result$values[which(result$lengths > 1)]
#> [1] "a" "b" "c"

相关问题