这是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::*
或其他方法?
4条答案
按热度按时间jobtbby31#
strsplit
返回一个列表,因此可以使用unlist
将字符串强制转换为单个字符向量,或者使用列表索引[[1]]
访问第一个元素。OR(请注意,实际上不需要命名
split
参数)您也可以在
NULL
或character(0)
上分割,以取得相同的结果。db2dz4w82#
stringr
中的str_extract_all()
提供了一种很好的方法来执行此操作:eanckbw93#
由于
stringr 1.5.0
,您可以使用str_split_1
,str_split
的一个版本,用于单个字符串: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