以下函数创建一个 data.frame,其中 n 列作为参数的数量
functionWithDots <- function(...) {
f1 <- function(x) c(x,x+4)
list <- list(...)
list <- lapply(list, f1)
expand.grid(list)
}
当运行它时
functionWithDots(1,2)
预期的结果是:
而如果我通过将“(1,2)”替换为“1:2”来做同样的事情
functionWithDots(1,2)
结果是
如何将正确的未连接参数传递给该函数,因为它在传递时似乎返回不同的结果,比如说“1,2,3”而不是“c(1,2,3)”?
最佳答案
假设我正确理解了问题,即。 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
核对对比 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
,该函数返回 list
的 length
1functionWithDots(1:2)
#[[1]]
#[1] 1 2
而在第二个中,它返回一个
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
关于r - 使用 "..."R 拆分函数的数组参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32007458/