Separate function array arguments with "..." R

The following function creates data.frame with n columns as the number of arguments

functionWithDots <- function(...) {
  f1 <- function(x) c(x,x+4)
  list <- list(...)
  list <- lapply(list, f1)
  expand.grid(list)
  }

When running functionWithDots (1,2) Expected Result:

  • id Var1 Var2
    • 12
    • 5 2
    • sixteen
    • 5 6

and if I do the same, replacing "(1,2)" with "1: 2" as

functionWithDots(1,2)

result

  • id Var1
    • one
    • 2
    • 5
    • 6

How can I pass the correct non-concatenated argument to these functions, since it seems to return different results when passing, say, "1,2,3" instead of "c (1,2,3)"?

+4
source share
1 answer

, , .. OP , 1,2 1:2 functionWithDots, . ... list , .

functionWithDots <- function(...) {
   f1 <- function(x) c(x,x+4)
   dots <- c(...)
   list <- as.list(dots)
   list <- lapply(list, f1)
   expand.grid(list)
 }


functionWithDots(1,2)
#  Var1 Var2
#1    1    2
#2    5    2
#3    1    6
#4    5    6
 functionWithDots(1:2)
#  Var1 Var2
#1    1    2
#2    5    2
#3    1    6
#4    5    6

1:3 vs 1,2,3

functionWithDots(1,2,3)
#  Var1 Var2 Var3
#1    1    2    3
#2    5    2    3
#3    1    6    3
#4    5    6    3
#5    1    2    7
#6    5    2    7
#7    1    6    7
#8    5    6    7

functionWithDots(1:3)
#  Var1 Var2 Var3
#1    1    2    3
#2    5    2    3
#3    1    6    3
#4    5    6    3
#5    1    2    7
#6    5    2    7
#7    1    6    7
#8    5    6    7

OP ( lapply expand.grid)

functionWithDots <- function(...) {
  f1 <- function(x) c(x,x+4)
  list <- list(...)
  print(list)
}

1:2 a list of length 1

functionWithDots(1:2)
#[[1]]
#[1] 1 2

- a list ,

functionWithDots(1,2)
#[[1]]
#[1] 1

#[[2]]
#[1] 2

list , .

functionWithDots <- function(...) {
  f1 <- function(x) c(x,x+4)
  dots <- c(...)
  list <- as.list(dots)
  print(list) 
 }

functionWithDots(1:2)
#[[1]]
#[1] 1

#[[2]]
#[1] 2

functionWithDots(1,2)
#[[1]]
#[1] 1

#[[2]]
#[1] 2
+2

All Articles