将字符向量拆分为单个字符? (与paste或stringr :: str_c相反)

时间:2014-04-12 10:01:26

标签: string r paste string-split stringr

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::*或其他任何内容?

2 个答案:

答案 0 :(得分:8)

是的,strsplit会这样做。 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)上拆分相同的结果。

答案 1 :(得分:3)

str_extract_all()中的

stringr提供了执行此操作的好方法:

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"