2

我需要根据当前行和对整个数据框列的一些计算来获取我的数据框的一个子集。我正在尝试使用 R 的向量表示法根据自定义函数过滤掉不需要的行:

myDataFrame[customFn(myDataFrame$A, ????? <<here I need to reference not just the current value of myDataFrame$A, but the whole vector myDataFrame$A>> ),]

我的 customFn 有 2 个参数:一个数字和一个向量,它返回一个布尔向量。如何将整个列向量传递给函数?我不想使用 apply 因为我认为它会比矢量过滤慢得多

谢谢!

4

1 回答 1

3

正如@Justin 指出的那样-只要customFn返回与数据框长度相同的逻辑向量,就可以了。例如

# Define a function to return a vector of logicals based on the mtcars$mpg
keepers <- function(d, lower=18, upper=20) {
  to_keep <- rep(TRUE, nrow(d))
  to_keep[(d$mpg < lower) | (d$mpg > upper)] <- FALSE
  to_keep # True if d$mpg is between upper and lower
}

mtcars[keepers(mtcars), ]
于 2013-11-14T16:53:46.497 回答