Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

R retrieving values from data.tables while within custom functions

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading