[R] concatenate vector after strsplit()

Gabor Grothendieck ggrothendieck at gmail.com
Sun Feb 20 19:17:26 CET 2011


On Sun, Feb 20, 2011 at 12:43 PM, Robert Baer <rbaer at atsu.edu> wrote:
>> You might try
>>
>> do.call(rbind, lapply(yourlist, "[", 1:4))
>
> Thanks, Jorge, but when I tried this I simply got a matrix of character
> strings rather than my original list of character strings as in:
>>
>> m = do.call(rbind, lapply(ls, "[", 1:4))
>> m
>
>     [,1]      [,2]  [,3]  [,4]
> [1,] "Focused" "10k" "A12" "t04.tif"
> [2,] "Focused" "10k" "A12" "t08.tif"
> [3,] "Focused" "10k" "A12" "t12.tif"
> [4,] "Focused" "10k" "A12" "t16.tif"
> [5,] "Focused" "10k" "A12" "t20.tif"
> [6,] "Focused" "10k" "A12" "t24.tif"
> [7,] "Focused" "10k" "A12" "t36.tif"
> [8,] "Focused" "10k" "A12" "t48.tif"
> [9,] "Focused" "10k" "B12" "t04.tif"
> [10,] "Focused" "10k" "B12" "t08.tif"
>>
> What I want to end up with is a vector that is the row-wise concatenation of
> the strings in each row of your matrix or each element of my original list.

Try this:

   sapply(ls, function(x) paste(x[1:4], collapse = ""))

or this:

   sapply(unname(as.data.frame(ls))[1:4,], paste, collapse = "")

If you don't mind ugly names on the result the last one can be shortened to:

   sapply(as.data.frame(ls)[1:4,], paste, collapse = "")

-- 
Statistics & Software Consulting
GKX Group, GKX Associates Inc.
tel: 1-877-GKX-GROUP
email: ggrothendieck at gmail.com



More information about the R-help mailing list