Access n-th element after string splitting

  • A+
Category:Languages

I have a string that looks like:

string <- c("A,1,some text,200", "B,2,some other text,300", "A,3,yet another one,100") 

So every vector element is further divided by commas. Now I only want to extract elements at a certain place. Let's say all the elements before the first comma or all the elements after the second comma.

The following code does what I want:

sapply(strsplit(string, ","), function(x){return(x[[1]])}) # [1] "A" "B" "A" sapply(strsplit(string, ","), function(x){return(x[[3]])}) # [1] "some text" "some other text" "yet another one" 

However this code seems fairly complicated to me (given the simplicity of the question). Are there more concise options to achieve what I want?

 


One option is to use word from stringr with sep argument

library(stringr) word(string, 1, sep = ",") #[1] "A" "B" "A"  word(string, 3, sep = ",") #[1] "some text"       "some other text" "yet another one" 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: