1

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)

1
  • 1
    which(unlist(strsplit(a, split="")) == 1) will do it. you have to pull the vector out of the list with unlist. Commented Dec 23, 2016 at 13:49

2 Answers 2

5

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
Sign up to request clarification or add additional context in comments.

1 Comment

Nice. I Keep forgetting about those regex functions.
0

Another option is str_locate from stringr

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.