[R] swapping with data.frame

Martin Maechler maechler at stat.math.ethz.ch
Wed Jun 2 22:30:06 CEST 2004


>>>>> "Eryk" == Eryk Wolski <wolski at molgen.mpg.de>
>>>>>     on Tue, 01 Jun 2004 20:03:03 +0200 writes:

    Eryk> Hi!  U can use.

    Eryk> rbind(t1,t2,t3)

yes, but not for getting a data frame!
nor does give
    as.data.frame( rbind(t1,t2,t3) )
give the correct result {make use of  str(.)  to see this quickly}

Correct (though not "extremely simple") is

     do.call("rbind", lapply(list(t1,t2,t3), as.data.frame))


> str(do.call("rbind", lapply(list(t1,t2,t3), as.data.frame)))
`data.frame':	       3 obs. of  5 variables:
 $ fname   : Factor w/ 2 levels "animal1","animal2": 1 1 2
 $ testname: Factor w/ 2 levels "hyla","bufo": 1 2 1
 $ dspkr   : Factor w/ 2 levels "left","right": 1 1 2
 $ res1    : num  39.7 14.4 22.6
 $ res2    : num  15 56.1 11.8



    Eryk> On 6/1/2004 at 10:55 AM Randy Zelick wrote:

    >> Hi there,
    >> 
    >> I have some data which are convenient to enter as
    >> lists. For example:
    >> 
    >> t1<-list(fname="animal1",testname="hyla",dspkr="left",res1=39.7,res2=15.0)
    >> t2<-list(fname="animal1",testname="bufo",dspkr="left",res1=14.4,res2=56.1)
    >> t3<-list(fname="animal2",testname="hyla",dspkr="right",res1=22.6,res2=11.8)
    >> 
    >> I would like to generate a dataframe, but *not* the way
    >> this approach works...
    >> 
    >> fdf<-data.frame(t1,t2,t3)
    >> 
    >> fdf
    >> 
    >> fname testname dspkr res1 res2 fname testname dspkr res1
    >> res2 ...  1 animal1 hyla left 39.7 15 animal1 bufo left
    >> 14.4 56.1 ...
    >> 
    >> 
    >> Instead, what I would like is:
    >> 
    >> fname testname dspkr res1 res2
    >> 
    >> t1 animal1 hyla left 39.7 15.0 t2 animal1 bufo left 14.4
    >> 56.1 t3 animal2 hyla right 22.6 11.8
    >> 
    >> 
    >> or this would be fine too...
    >> 
    >> x fname testname dspkr res1 res2
    >> 
    >> 1 t1 animal1 hyla left 39.7 15.0 2 t2 animal1 bufo left
    >> 14.4 56.1 3 t3 animal2 hyla right 22.6 11.8
    >> 
    >> Is there a practical (hopefully simple) way to do this?
    >> 
    >> Thanks,
    >> 
    >> =Randy=




More information about the R-help mailing list