R 在自定义函数中从 data.tables 中检索值

R retrieving values from data.tables while within custom functions

我正在尝试从数据中检索一个值table 作为更大的自定义函数的一部分。我可以生成行号,但无法从该行中检索值。该公式在函数环境外有效,但在函数环境内无效。

example_outlier_table <- data.table(dataset = c("doe", "ray", "me", "fa", "so"),
                                    upper_limit = c(2,6,9,11,7))

example_function <- function(dt,otable){
  return(match(deparse(substitute(dt)), otable$dataset))
}

example_function(ray, example_outlier_table)

结果 = 2

这是正确的,'ray' 是 'dataset' 列中的第二个条目

在这个例子中,'ray'既是'example_outlier_table$dataset'中的字符串,又是另一个数据table对象的名称,因此是'deparse(substitute(dt))'步骤。

问题是这样的:我想在自定义函数的另一个地方使用 'ray' 在 example_outlier_table 中指示的值,编号 6。

example_function <- function(dt,otable){
  return(otable[dataset == as.character(deparse(substitute(dt))), 
                upper_limit])
}

example_function(ray, example_outlier_table)

结果=数字(0) 不正确

example_function <- function(dt,otable){
  return(otable[match(deparse(substitute(dt)), otable$dataset), 
                upper_limit])
}

example_function(ray, example_outlier_table)

结果 = [1] 不适用

我们可以直接用 [[

提取列
example_function <- function(dt,otable){
   dt <- deparse(substitute(dt))
    otable[["upper_limit"]][otable[["dataset"]] == dt]
}

-测试

example_function(ray, example_outlier_table)
[1] 6

或使用data.table方法

example_function <- function(dt,otable){
   dt <- deparse(substitute(dt))
    otable[dataset == dt, upper_limit][[1]]
}
example_function(ray, example_outlier_table)
[1] 6