How do I split a string and store it in a list?

180 views Asked by At

I have a string a="100111" and want to split it and store as b=("1","0","0","1","1","1") as a list with length =6. I tried splitting using srtsplit but I end up with a list b = ("1" "0" "0" "1" "1" "1"), with length = 1. The end goal is to get which positions in the string "100111" has 1. For example when I split a and store it in b as ("1","0","0","1","1","1") and then use which(b=='1') it want to get (1,4,5,6)

2

There are 2 answers

0
akrun On

Another option is str_locate from stringr

library(stringr)
str_locate_all(a, "1")[[1]][,1]
#[1] 1 4 5 6
1
G. Grothendieck On

gregexpr will give the positions of 1's in the string without having to actually split it:

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