我想在函数中创建交叉联接data.table
。说,我们有一个向量vals <- c("yes", "no")
。现在这个有效:CJ(vals, vals)
。但是,根据功能输入,我可能需要创建例如而是CJ(vals, vals, vals, vals)
。像
vals <- c("yes", "no")
n <- 4
CJ(rep(vals, n))
显然不会工作。如何以灵活的方式指定交叉连接的向量?
答案 0 :(得分:5)
您可以使用...
来表示从调用函数传递的参数...?
require( data.table )
f <- function( ... ){
CJ(...)
}
f( c(1:2) , c(3:4) )
# V1 V2
#1: 1 3
#2: 1 4
#3: 2 3
#4: 2 4
编辑:这个怎么样?
do.call(CJ, replicate(n, vals, simplify=FALSE))
# V1 V2 V3 V4
# 1: no no no no
# 2: no no no yes
# 3: no no yes no
# 4: no no yes yes
# 5: no yes no no
# 6: no yes no yes
# 7: no yes yes no
# 8: no yes yes yes
# 9: yes no no no
# 10: yes no no yes
# 11: yes no yes no
# 12: yes no yes yes
# 13: yes yes no no
# 14: yes yes no yes
# 15: yes yes yes no
# 16: yes yes yes yes