0

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?

Lieke
  • 127
  • 11
  • It's easier to help you if you provide a [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output that can be used to test and verify possible solutions. – MrFlick May 04 '22 at 14:03

2 Answers2

2

You can use lapply(), and do.call()

do.call(rbind, lapply(l1, f1))
langtang
  • 22,248
  • 1
  • 12
  • 27
1

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)
       )