[R] Converting BY to a data.frame

David Winsemius dwinsemius at comcast.net
Tue Jan 10 21:01:42 CET 2012


On Jan 10, 2012, at 1:36 PM, Ramiro Barrantes wrote:

> Hello,
>
> I am trying to convert BY to a data frame, consider the following  
> example:
>
> exampleDF<-data.frame(a=c(1,2),b=c(10,20),name=c("first","second"))
> exampleBY<-by(exampleDF,with(exampleDF,paste(a,b,sep="_")),
>               function(x) {
>                 data.frame(
>                     name=as.character(x$name),
>                     a=x$a,
>                     b=x$b,
>                     c=x$a + x$b)
>               }
>         )
>

It would be less confusing when the time comes around to coercing  
vectors if you added stringsAsFactors =FALSE

exampleBY<-by(exampleDF,with(exampleDF,paste(a,b,sep="_")),
               function(x) {
                 data.frame(
                     name=as.character(x$name),
                     a=x$a,
                     b=x$b,
                     c=x$a + x$b, stringsAsFactors=FALSE)
               }

Then just:

do.call(rbind, exampleBY)
        name a  b  c
1_10  first 1 10 11
2_20 second 2 20 22


> I made this function:
>
> convertByToDataFrame <- function( byObject ) {
> data 
> .frame 
> (matrix 
> (unlist 
> (byObject 
> ),nrow 
> = 
> length 
> (byObject 
> ),ncol 
> = 
> length 
> (byObject[[1]]),byrow=TRUE,dimnames=list(NULL,names(byObject[[1]]))))
> }
>
> but when I run it:
> convertByToDataFrame(exampleBY)
>
> I either: (1) loose the types of the different values in the BY, or  
> 2) get factors instead of the values
>
> I tried the following but it doesn't scale:
>
> exampleSUMRY <- data.frame(a =  
> as 
> .vector 
> (unlist(lapply(strsplit(names(exampleBY),split="_"),function(x)  
> x[1]))),
>                            b =  
> as 
> .vector 
> (unlist(lapply(strsplit(names(exampleBY),split="_"),function(x)  
> x[2]))),
>                             
> name=as.vector(unlist(lapply(exampleBY,function(x) x[[1]]))))
>
> Any suggestions?
>
> Thank you,
> Ramiro
> 	[[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.

David Winsemius, MD
West Hartford, CT



More information about the R-help mailing list