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::*
或其他任何内容?
答案 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"
您也可以在NULL
或character(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"