Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an R function which can pass elements of lists as arguments without specifying individual elements

Tags:

list

r

Is there an R function which can pass all the elements of a list as the arguments of a function?

library(tidyr)
a <- c(1,2,3)
b <- c(4,5,6)
c <- c(7,8,9)
d <- list(a,b,c)
crossing(d[[1]],d[[2]],d[[3]])

Instead of specifying d[[1]],d[[2]],d[[3]], i'd like to just include d

Expected result:

> crossing(d[[1]],d[[2]],d[[3]])
# A tibble: 27 x 3
   `d[[1]]` `d[[2]]` `d[[3]]`
      <dbl>    <dbl>    <dbl>
 1        1        4        7
 2        1        4        8
 3        1        4        9
 4        1        5        7
 5        1        5        8
 6        1        5        9
 7        1        6        7
 8        1        6        8
 9        1        6        9
10        2        4        7
# ... with 17 more rows
like image 658
Ali Avatar asked Nov 17 '25 09:11

Ali


1 Answers

You can use do.call to executes a function call and a list of arguments to be passed to it.

c(d[[1]],d[[2]],d[[3]])
#[1] 1 2 3 4 5 6 7 8 9

do.call("c", d)
#[1] 1 2 3 4 5 6 7 8 9

And for crossing, which needs not duplicated Column names:

library(tidyr)
names(d) <- seq_along(d)
do.call(crossing, d)
## A tibble: 27 x 3
#     `1`   `2`   `3`
#   <dbl> <dbl> <dbl>
# 1     1     4     7
# 2     1     4     8
# 3     1     4     9
# 4     1     5     7
# 5     1     5     8
# 6     1     5     9
# 7     1     6     7
# 8     1     6     8
# 9     1     6     9
#10     2     4     7
## … with 17 more rows
like image 52
GKi Avatar answered Nov 19 '25 23:11

GKi