Home > Software design >  R retrieving values from data.tables while within custom functions
R retrieving values from data.tables while within custom functions

Time:03-22

I'm trying to retrive a value from a datatable as part of a larger custom function. I can gnerate the row number, but I can't retrive the values from that row. The formula works outside of the function environment but not inside.

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)

result = 2

This is correct, 'ray' is the second entry in the 'dataset' column

In this example, 'ray' is both the character string in 'example_outlier_table$dataset' and the name of another data table object, hence the 'deparse(substitute(dt))' step.

The issue is this: I want to use the value that 'ray' indicates in the example_outlier_table, number 6, in another place within my custom function.

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

example_function(ray, example_outlier_table)

result = numeric(0) incorrect

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

example_function(ray, example_outlier_table)

result = [1] NA

CodePudding user response:

We could directly extract the column with [[

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

-testing

example_function(ray, example_outlier_table)
[1] 6

Or using the data.table methods

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