The way via unlist
and matrix
seems a bit convoluted, and requires you to hard-code the number of elements (this is actually a pretty big no-go. Of course you could circumvent hard-coding that number and determine it at run-time)
I would go a different route, and construct a data frame directly from the list that strsplit
returns. For me, this is conceptually simpler. There are essentially two ways of doing this:
as.data.frame
– but since the list is exactly the wrong way round (we have a list of rows rather than a list of columns) we have to transpose the result. We also clear the rownames
since they are ugly by default (but that’s strictly unnecessary!):
`rownames<-`(t(as.data.frame(strsplit(text, '\\.'))), NULL)
Alternatively, use rbind
to construct a data frame from the list of rows. We use do.call
to call rbind
with all the rows as separate arguments:
do.call(rbind, strsplit(text, '\\.'))
Both ways yield the same result:
[,1] [,2] [,3] [,4]
[1,] "F" "US" "CLE" "V13"
[2,] "F" "US" "CA6" "U13"
[3,] "F" "US" "CA6" "U13"
[4,] "F" "US" "CA6" "U13"
[5,] "F" "US" "CA6" "U13"
[6,] "F" "US" "CA6" "U13"
…
Clearly, the second way is much simpler than the first.