Learner
Learner

Reputation: 639

Working out the output of strsplit in R

I have the following string expression, to which I apply strsplit:

x="Hello I am using stack overflow to ask this question."
y=strsplit(x,"a")

The above function splits x when ever there is an 'a'. From my understanding, the returned vector should be a list, and so say I wanted to get the second fragment of x, I should be using:

y[[2]]

However, this gives me an error:

Error in y[[2]] : subscript out of bounds

I am not sure how to resolve this. All I want is to access the broken fragments of the string.

Upvotes: 2

Views: 3980

Answers (1)

akrun
akrun

Reputation: 887048

The strsplit does return a list. But, the list is only a single element list.

length(strsplit(x,'a'))
#[1] 1

To access, the 2nd string of a single element list,

strsplit(x,"a")[[1]][2]
#[1] "m using st"

Suppose, if you have a vector of elements

 a1 <- rep(x,3)

The strsplit returns a list with number of elements equal to the length of a1

 lst <- strsplit(a1,'a')

To get the 2nd split string from the lst

 sapply(lst,`[`,2)
 #[1] "m using st" "m using st" "m using st"

Upvotes: 10

Related Questions