r - 为什么在将子集应用于 R 中的数据框列表时找不到函数传递的参数

标签 r subset sapply

我在 sapply subset 到 R 说“Error in eval(expr, envir, enclos) : 找不到对象 'thresh'”。我想知道为什么会这样。

test<-list()
test[[1]]<-as.data.frame(matrix(rnorm(50*5,10,100),50,5))
test[[2]]<-as.data.frame(matrix(rnorm(50*5,10,100),50,5))


findmax<-function(test,thresh){
  print(thresh)
  max(unlist(sapply(test,subset,V1>thresh,select=c("V1"))))
}

findmax(test,thresh=10)

最佳答案

请注意 ?subset 中的警告:

Warning:

     This is a convenience function intended for use interactively.
     For programming it is better to use the standard subsetting
     functions like ‘[’, and in particular the non-standard evaluation
     of argument ‘subset’ can have unanticipated consequences.

subset 有一些关于在其中查找对象和变量的奇怪的评估规则,这取决于调用环境等。当用户在顶层交互式调用时,这些规则工作正常,但通常如您所见,包裹在函数内部时失败。

这是使用标准子集重写函数的一种方法:

findmax <- function(test, thresh, want) {
    foo <- function(x, thresh, want) {
       take <- x[, want] > thresh
       x[take, want]
    }
    max(unlist(sapply(test, foo, thresh = thresh, want = want)))
}
findmax(test, thresh = 10, want = "V1")

您的测试数据给出:

R> findmax(test, thresh = 10, want = "V1")
[1] 230.9756

关于r - 为什么在将子集应用于 R 中的数据框列表时找不到函数传递的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12244534/

相关文章:

r - 在dplyr中,如何删除和重命名不存在的列,操作所有名称,并使用字符串命名新变量?

r - R 中具有时间条件的子集数据集

r - 循环遍历未命名的列以在 R 中的一张图上绘制

r - 伪 RNG 的不同行为取决于 R 的版本

r - 使用 ts 对象或 xts 对象的 ccf 提供不同的滞后

r - 数据框的所有列中包含数字的子集行

module - 可以在 Raku 中导出子集吗?

R:计算字符串列表中的所有组合(特定顺序)

R - 在列中查找模式并替换它(更有效的解决方案)

r - ggplot2错误:手动刻度中的值不足