I am reading everywhere that you should not use for-loops in R, but rather do it 'vectorized'. However I find for-loops intuitive and struggle with transforming my code.
I have a function f1 that I want to use multiple times. The inputs for the function are in a list called l1. My f1 outputs a df. I want to rbind these output dfs into one df. The for loop I have now is this:
z3 <- data.frame()
for(i in l1) {
z3 <- rbind(z3, f1(i))
}
Could anyone help me to do the same, but without the for-loop?
CodePudding user response:
You can use lapply()
, and do.call()
do.call(rbind, lapply(l1, f1))
CodePudding user response:
another more verbose approach:
## function that returns a 1 x 2 dataframe:
get_fresh_straw <- function(x) data.frame(col1 = x, col2 = x * pi)
l1 = list(A = 1, B = 5, C = 2)
Reduce(l1,
f = function(camel_back, list_item){
rbind(camel_back, get_fresh_straw(list_item))
},
init = data.frame(col1 = NULL, col2 = NULL)
)