简体   繁体   English

如何应用操作data.table的函数并将2个或多个值用作参数R

[英]How do I apply a function that operates a data.table and use 2 or more values as a parameter R

I have the following 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

And I want to recreate the following operation using a function 我想使用一个函数重新创建以下操作

k[v3 %in% unique(k$v3) & v4=="up",list("sum" = sum(v1)),by=v2]
   v2 sum
1: US   6
2: CA   2

So far I got this 到目前为止,我知道了

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

How can I enhance this function to be able to use more than one parameter in each expression, y,z. 我如何增强此功能,以便能够在每个表达式y,z中使用多个参数。 I have tried with the following function, setting an option called "All" that is a vector of all unique values of each column but it returns a data.table with zero rows 我尝试使用以下功能,设置一个名为“ All”的选项,该选项是每一列的所有唯一值的向量,但它返回的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)
}

This should get you started: 这应该使您开始:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用两个或更多列中的数据与R data.table的比较来应用函数 - How do I apply a function using comparisons of data in two or more columns with R data.table 如何将 ConvertColor 函数应用于 R 中 data.table 中列出的 RGB 值 - How to apply ConvertColor function to RGB values listed in a data.table in R 如何通过 R 中的多个列将 function 应用于 data.table 子集? - How to apply a function to a data.table subset by multiple columns in R? 如何将函数应用于data.table的行子集,其中每个调用返回data.table - How do I apply a function to row subsets of a data.table where each call returns a data.table 如何基于函数参数转换r data.table对象 - How to transform r data.table object based on function parameter 如何在data.table上运行apply? - How do I run apply on a data.table? R data.table 将 function 应用于使用列作为 ZDBC11CAA5BDA99F77E6FB4DABD8E 的行返回的多个值(A向量) - R data.table apply function to rows using columns as arguments which returns a vector (i.e. multiple values) 如何使用查找表替换data.table列中的值? [R] - How do I replace values in a data.table's column using a look up table? [R] 如何在 R 中的 data.table 中使用自定义函数 - How to use a custom function in data.table in R 如何在具有相同名称的列的 data.table 内引用函数参数? - How do I reference a function parameter inside inside a data.table with a column of the same name?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM