问题描述
R 中一个令人难以置信的基本问题,但解决方案尚不清楚.
An incredibly basic question in R yet the solution isn't clear.
如何将字符向量拆分为单个字符,即 paste(..., sep='')
或 stringr::str_c()
?
How to split a vector of character into its individual characters, i.e. the opposite of paste(..., sep='')
or stringr::str_c()
?
任何不那么笨重的东西:
Anything less clunky than this:
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::*
还是别的什么?
Can it be done otherwise, e.g. with strsplit()
, stringr::*
or anything else?
推荐答案
是的,strsplit
会做到的.strsplit
返回一个列表,因此您可以使用 unlist
将字符串强制转换为单个字符向量,或者使用列表索引 [[1]]
访问第一个元素.
Yes, strsplit
will do it. strsplit
returns a list, so you can either use unlist
to coerce the string to a single character vector, or use the list index [[1]]
to access first element.
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
参数)
OR (noting that it is not actually necessary to name the split
argument)
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)
以获得相同的结果.
You can also split on NULL
or character(0)
for the same result.
这篇关于将字符向量拆分为单个字符?(与 paste 或 stringr::str_c 相反)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!