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))))
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.
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.
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.
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.
Try
library(dplyr)
lapply(my_vector, my_function) %>% bind_rows()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With