Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a "by" object to a data frame in R

I'm using the "by" function in R to chop up a data frame and apply a function to different parts, like this:

pairwise.compare <- function(x) {
Nright <- ...
Nwrong <- ...
Ntied <- ...
return(c(Nright=Nright, Nwrong=Nwrong, Ntied=Ntied))
}
Z.by <- by(rankings, INDICES=list(rankings$Rater, rankings$Class), FUN=pairwise.compare)

The result (Z.by) looks something like this:

: 4 
: 357 
Nright Nwrong Ntied
     3      0     0
------------------------------------------------------------
: 8 
: 357 
NULL
------------------------------------------------------------
: 10 
: 470 
Nright Nwrong Ntied
     3      4     1 
------------------------------------------------------------ 
: 11 
: 470 
Nright Nwrong Ntied
    12      4     1

What I would like is to have this result converted into a data frame (with the NULL entries not present) so it looks like this:

  Rater Class Nright Nwrong Ntied
1     4   357      3      0     0
2    10   470      3      4     1
3    11   470     12      4     1

How do I do that?

like image 314
Lorin Hochstein Avatar asked Apr 12 '10 02:04

Lorin Hochstein


People also ask

How do I convert an object to a Dataframe in R?

frame() function in R Programming Language is used to convert an object to data frame. These objects can be Vectors, Lists, Matrices, and Factors.

Which function coerces an existing object to a data frame if possible?

as_tibble() turns an existing object, such as a data frame or matrix, into a so-called tibble, a data frame with class tbl_df .


1 Answers

The by function returns a list, so you can do something like this:

data.frame(do.call("rbind", by(x, column, mean)))
like image 80
Shane Avatar answered Oct 29 '22 11:10

Shane