[R] convert a vector of words into a matrix

Wacek Kusnierczyk Waclaw.Marcin.Kusnierczyk at idi.ntnu.no
Thu Jul 24 13:10:06 CEST 2008


Wacek Kusnierczyk wrote:
> Daren Tan wrote:
>   
>> I want the matrix to look like this:
>>  
>>       [,1] [,2] [,3] [,4]
>> [1,] "1" "2" "3"
>> [2,] "1" "2" [3,] "1" "2" "4" "5"
>>  
>> I tried to use do.call(rbind, strings) but failed due to unequal row lengths.
>>   
>>     
> you can't {r,c}bind them because of different lengths.
> one way to reach the goal is to pad all vectors with some dummy value
> (NA, say), and then bind them.
>
> one way (assuming strings is the list you get out of strsplit):
>
> lengths = sapply(strings, length)
> ncol = max(lengths)
>
> t(
>     mapply(
>        function(vector, length)
>             c(vector, rep(NA, ncol-length)),
>        strings,
>        lengths))
>
> there may be a better way, though.
>
>   
an alternative and more efficient solution using a for loop:

lengths = sapply(strings, length)
m = matrix(NA, nrow=length(strings), ncol=max(lengths))
for (row in 1:length(strings))
    m[i, 1:lengths[i]] = strings[[i]]

vQ



More information about the R-help mailing list