ldply rename variables

293 views
Skip to first unread message

Ross Ahmed

unread,
Feb 13, 2013, 3:49:14 AM2/13/13
to manip...@googlegroups.com
Does the output from ldply allow variables to be named, for example:

ldply(mtcars, function(x) mean(x))

gives a dataframe with column names automatically assigned to '.id' and 'V1'. Can the columns names be stated within the ldply function (as in ddply)?


Brandon Hurr

unread,
Feb 13, 2013, 5:32:50 AM2/13/13
to Ross Ahmed, manipulatr
ldply(mtcars, function(model) {c(variablename=mean(model))})

It looks like it has to be wrapped a bit. 


--
You received this message because you are subscribed to the Google Groups "manipulatr" group.
To unsubscribe from this group and stop receiving emails from it, send an email to manipulatr+...@googlegroups.com.
To post to this group, send email to manip...@googlegroups.com.
Visit this group at http://groups.google.com/group/manipulatr?hl=en.
For more options, visit https://groups.google.com/groups/opt_out.
 
 

Ista Zahn

unread,
Feb 13, 2013, 7:37:39 AM2/13/13
to Brandon Hurr, Ross Ahmed, manipulatr
The documentation says

"The most unambiguous behaviour is achieved when ‘.fun’ returns a
data frame - in that case pieces will be combined with
‘rbind.fill’. If ‘.fun’ returns an atomic vector of fixed length,
it will be ‘rbind’ed together and converted to a data frame. Any
other values will result in an error."

So in my view the better way is

ldply(mtcars, function(x) data.frame(mean=mean(x)))

Best,
Ista

Hadley Wickham

unread,
Feb 13, 2013, 7:41:48 AM2/13/13
to Ista Zahn, Brandon Hurr, Ross Ahmed, manipulatr
> "The most unambiguous behaviour is achieved when ‘.fun’ returns a
> data frame - in that case pieces will be combined with
> ‘rbind.fill’. If ‘.fun’ returns an atomic vector of fixed length,
> it will be ‘rbind’ed together and converted to a data frame. Any
> other values will result in an error."
>
> So in my view the better way is
>
> ldply(mtcars, function(x) data.frame(mean=mean(x)))

Or ldply(mtcars, "mean"), since there the name of the function is known.

Hadley

--
Chief Scientist, RStudio
http://had.co.nz/

Ista Zahn

unread,
Feb 13, 2013, 7:44:22 AM2/13/13
to Hadley Wickham, Brandon Hurr, Ross Ahmed, manipulatr
On Wed, Feb 13, 2013 at 7:41 AM, Hadley Wickham <h.wi...@gmail.com> wrote:
>> "The most unambiguous behaviour is achieved when ‘.fun’ returns a
>> data frame - in that case pieces will be combined with
>> ‘rbind.fill’. If ‘.fun’ returns an atomic vector of fixed length,
>> it will be ‘rbind’ed together and converted to a data frame. Any
>> other values will result in an error."
>>
>> So in my view the better way is
>>
>> ldply(mtcars, function(x) data.frame(mean=mean(x)))
>
> Or ldply(mtcars, "mean"), since there the name of the function is known.

Right! I always forget about that.
Reply all
Reply to author
Forward
0 new messages