I was trying to figure out how to deal better with strsplit output. I often have data that I would like to share:
mydata <- c("144/4/5", "154/2", "146/3/5", "142", "143/4", "DNB", "90") #[1] "144/4/5" "154/2" "146/3/5" "142" "143/4" "DNB" "90"
After cleavage, the results are as follows:
strsplit(mydata, "/") #[[1]] #[1] "144" "4" "5" #[[2]] #[1] "154" "2" #[[3]] #[1] "146" "3" "5" #[[4]] #[1] "142" #[[5]] #[1] "143" "4" #[[6]] #[1] "DNB" #[[7]] #[1] "90"
I know from the strsplit reference manual that final empty lines are not created. Therefore, in each of my results there will be 1, 2 or 3 elements based on the number "/" to be divided into
Getting the first element is very trivial:
sapply(strsplit(mydata, "/"), "[[", 1) #[1] "144" "154" "146" "142" "143" "DNB" "90"
But I'm not sure how to get the 2nd, 3rd ... when each result has an unequal number of elements.
sapply(strsplit(mydata, "/"), "[[", 2)
I would like to return from a working solution, the following:
#[1] "4" "2" "3" "NA" "4" "NA" "NA"
This is a relatively small example. I could do some for the loop very easily on this data, but for real data with 1000s of observations to run strsplit and dozens of elements derived from this, I was hoping to find a more generalized solution.