Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to combine result of lapply to a data.frame?

Tags:

r

dplyr

Say, I have a vector and a function with one argument which returns a data.frame. I want to apply the function to each element of the vector and combine the results to one big data.frame.

I've got the working command below with lapply and rbind. But it looks to me a little bit "unnatural". Is there a better, more clear way? I've got some ideas with plyr but I would like to avoid plyr because I would like to use dplyr instead.

 my_vector <- c(1,2,3)
 my_function <- function(a){
   unif <- runif(a)
   norm <- rnorm(a)
   return(data.frame(unif=unif, norm=norm))
 }

 as.data.frame(do.call(rbind,(lapply(my_vector, my_function))))
like image 219
JerryWho Avatar asked Feb 22 '15 12:02

JerryWho


People also ask

Can you use Lapply on a Dataframe?

lapply() on a data frame. If, instead of a list, you had a data frame of stock returns, could you still use lapply() ? Yes! Perhaps surprisingly, data frames are actually lists under the hood, and an lapply() call would apply the function to each column of the data frame.

Can you use Lapply on a Dataframe in R?

In R Programming Language to apply a function to every integer type value in a data frame, we can use lapply function from dplyr package. And if the datatype of values is string then we can use paste() with lapply.

How do I combine two data frames with different number of rows?

Use the full_join Function to Merge Two R Data Frames With Different Number of Rows. full_join is part of the dplyr package, and it can be used to merge two data frames with a different number of rows.

What function join two or more column vectors to form a data frame?

rbind(): combining vectors or lists with equal number of columns. All columns must be of the same data type. For example, character columns cannot be combined with numeric columns. rbind() is the equivalent of stacking data sets on top of each other.


1 Answers

Try

library(dplyr)
lapply(my_vector, my_function) %>% bind_rows()
like image 72
Khashaa Avatar answered Sep 24 '22 08:09

Khashaa