I\'ve been trying to understand how to deal with the output of strsplit a bit better. I often have data such as this that I wish to split:
myd
Try this:
> read.table(text = mydata, sep = "/", as.is = TRUE, fill = TRUE)
V1 V2 V3
1 144 4 5
2 154 2 NA
3 146 3 5
4 142 NA NA
5 143 4 NA
6 DNB NA NA
7 90 NA NA
If you want to treat DNB as an NA then add the argument na.strings="DNB" .
If you really want to use strsplit then try this:
> do.call(rbind, lapply(strsplit(mydata, "/"), function(x) head(c(x,NA,NA), 3)))
[,1] [,2] [,3]
[1,] "144" "4" "5"
[2,] "154" "2" NA
[3,] "146" "3" "5"
[4,] "142" NA NA
[5,] "143" "4" NA
[6,] "DNB" NA NA
[7,] "90" NA NA
Note: Using alexis_laz's observation that x[i] returns NA if i is not in 1:length(x) the last line of code above could be simplified to:
t(sapply(strsplit(mydata, "/"), "[", 1:3))