Leo5188
Leo5188

Reputation: 2067

How to handle "by" class returned by using by() function in R

I am using a by() function in R to run A FUN() on all subsets of a factor. The FUN() returns two numbers as its returning values. The by() function returns a "by" class like this:

--------------------------------------------------------------------------------------- 
: 98012
[1] 25.00  0.84
--------------------------------------------------------------------------------------- 
: 98301
[1] 5.0 0.6
--------------------------------------------------------------------------------------- 

I'd like to convert this "by" class into an ordinary data.frame so that I can use two returned numbers separately. However, such "by" class cannot be converted into a data.frame. Any ideas?

Upvotes: 0

Views: 1323

Answers (2)

digEmAll
digEmAll

Reputation: 57220

You can do:

df <- do.call(cbind.data.frame, yourByResult)

Notice that you need to specify the cbind.data.frame otherwise, by using the simple cbind the result will be a matrix instead of a data.frame.

Upvotes: 3

Justin
Justin

Reputation: 43265

I'd say just don't use by!

Instead use ddply from the plyr package with the syntax

ddply(data.frame,splitting-variable,f())

the key is that your function needs to take a data.frame and return a data.frame.

Upvotes: 2

Related Questions