Re: [R] splitting a character field in R

From: Na Li <nali_at_umn.edu>
Date: Sat 29 Oct 2005 - 03:18:13 EST

On 28 Oct 2005, ManuelPerera-Chang@fmc-ag.com wrote:

> A<-c(1,2,3)
> B<-c("dgabcrt","fgrtabc","sabcuuu")
> C<-strsplit(B,"abc")
> > C
> [[1]]
> [1] "dg" "rt"
>
> [[2]]
> [1] "fgrt"
>
> [[3]]
> [1] "s" "uuu"
>
> Which looks promissing, but here C is a list with three elements. But how
> to create the two vectors I need from here, that is
>
> ("dg","fgrt", "s") and ("rt","","uuu")

To convert a list to a matrix

> do.call ("rbind", C)

     [,1] [,2]

[1,] "dg"   "rt"  
[2,] "fgrt" "fgrt"
[3,] "s"    "uuu" 

is good trick. However, it doesn't work as intended here since the elements of C have difference lengths. It would be nice to have 'rbind' and 'cbind' allow different ways of padding the vectors into the same length.

One work around is:

> sapply (C, function (x) x[1:2])

     [,1] [,2] [,3]
[1,] "dg" "fgrt" "s"
[2,] "rt" NA "uuu"

You may convert the NA's to "" if you want.

Michael



R-help@stat.math.ethz.ch mailing list
https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html Received on Sat Oct 29 03:39:17 2005

This archive was generated by hypermail 2.1.8 : Sat 29 Oct 2005 - 06:16:09 EST