manoj1123
manoj1123

Reputation: 125

Trying to write a dplyr version of plyr::ldply

I could get the expected dataframe with the following code.

plyr::ldply(1:10, function(x){mean(sample(1:6, 2, replace = T))})  

However can I reproduce the result using any dplyr version. Not able to use dplyr::do() function as it does not accept class of numeric or integer variables.

Upvotes: 1

Views: 326

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 388982

You should use purrr functions here instead of dplyr :

For example with map_dbl :

library(purrr)
data.frame(V1 = map_dbl(1:10, function(x){mean(sample(1:6, 2, replace = T))}))

Or with map_df :

map_df(1:10, function(x){data.frame(V1 = mean(sample(1:6, 2, replace = T)))})

The same can be done in base R with sapply :

data.frame(V1 = sapply(1:10, function(x){mean(sample(1:6, 2, replace = T))}))

Upvotes: 2

Related Questions