我有以下data.table
k
v1 v2 v3 v4
1: 1 US a up
2: 2 CA a up
3: 3 US b down
4: 4 CA a down
5: 5 US b up
6: 6 CA b down
我想使用函数
重新创建以下操作k[v3 %in% unique(k$v3) & v4=="up",list("sum" = sum(v1)),by=v2]
v2 sum
1: US 6
2: CA 2
到目前为止我得到了这个
myfun <- function(x,y,z) {
w <- x[v3 %in% y & v4 %in% z,list("sum" = sum(v1)),by=v2]
print(w)
}
myfun(k,"a","up")
v2 sum
1: US 1
2: CA 2
如何增强此功能,以便在每个表达式y,z中使用多个参数。我尝试使用以下功能,设置一个名为&#34; All&#34;的选项。这是每列所有唯一值的向量,但它返回一个零行的data.table
myfun <- function(x,y,z) {
ifelse(y == "All" ,y==unique(x$v3),y==y)
ifelse(z == "All" ,z==unique(x$v2),z==z)
w <- x[v3 %in% y & v4 %in% z,list("sum" = sum(v1)),by=v2]
print(w)
}
答案 0 :(得分:4)
这应该让你开始:
myfun <- function(x,y,z) {
if (length(y) == 1 && y == "All") {
cond1 = TRUE
} else {
cond1 = quote(v3 %in% y)
}
if (length(z) == 1 && z == "All") {
cond2 = TRUE
} else {
cond2 = quote(v4 %in% z)
}
x[eval(cond1) & eval(cond2), list("sum" = sum(v1)), by=v2]
}
myfun(k, "a", "up")
# v2 sum
#1: US 1
#2: CA 2
myfun(k, "All", "up")
# v2 sum
#1: US 6
#2: CA 2