Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rbind the list returned from a function without loop in R

In R, for a function whose input is one variable and output is a list, how can I apply the function to a list of inputs and combine the output lists into one data frame or matrix?

For example:

fun = function(x){
    list = c(x, x+1, x+2)
    return(list)
}

Now I'd like to apply fun() to a list, say

list = c(1,11,21)

The result should be

1,2,3
11,12,13
21,22,23

I know do.call and loop will do it. But is there a better way of doing it, perhaps without looping? The actual function is too big and too slow, I would rather not looping it.

like image 282
user7453767 Avatar asked Jun 22 '26 03:06

user7453767


2 Answers

We can use lapply :

do.call(rbind, lapply(list, fun))

#     [,1] [,2] [,3]
#[1,]    1    2    3
#[2,]   11   12   13
#[3,]   21   22   23

Instead of numeric vector if you return a named list, you can use map.* functions from purrr.

fun = function(x){
  list = list(a = x, b = x+1, c = x+2)
  return(list)
}

purrr::map_df(list, fun)
#OR
#purrr::map_dfr(list, fun)

#     a     b     c
#  <dbl> <dbl> <dbl>
#1     1     2     3
#2    11    12    13
#3    21    22    23
like image 155
Ronak Shah Avatar answered Jun 24 '26 21:06

Ronak Shah


If you want a matrix, sapply is probably sufficient.

lst <- c(1,11,21)  ## don't use `list` since it is a function name!

t(sapply(lst, fun))
#      [,1] [,2] [,3]
# [1,]    1    2    3
# [2,]   11   12   13
# [3,]   21   22   23
like image 32
jay.sf Avatar answered Jun 24 '26 19:06

jay.sf



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!