如何拆分字符串并将其存储在列表中?

时间:2016-12-23 13:45:15

标签: r strsplit

我有一个字符串a="100111",想要将其拆分并存储为b=("1","0","0","1","1","1")作为长度为6的列表。我尝试使用srtsplit进行拆分,但最终得到一个列表b = ("1" "0" "0" "1" "1" "1"),长度为1.最终目标是获取字符串"100111"中的哪些位置为1.例如,当我拆分并存储时它在b中为("1","0","0","1","1","1"),然后使用which(b=='1')它想要(1,4,5,6)

2 个答案:

答案 0 :(得分:5)

gregexpr会在字符串中给出1的位置,而不必实际拆分它:

unlist(gregexpr("1", "100111"))
## [1] 1 4 5 6

答案 1 :(得分:0)

另一个选项是来自str_locate

stringr
library(stringr)
str_locate_all(a, "1")[[1]][,1]
#[1] 1 4 5 6