Search code examples
rfunction

How can I build a function in R that will take a numerical variable as a column name?


I am trying to create a function that will use a number it is passed as a column name for a dataframe. This sounds sort of silly because normally I wouldn't use numbers as column names, but in this case I'm actually trying to work with a BchronCalibratedDates object produced by the Bchron package, and it is a nested list named after the sample ID, which is usually a number.

Anyway, a simple reproducible example of what I'm trying to do would be something like:

a <- 1:5
dat <- tibble("1" = a, "2" = a*2)

test <- function(x) {
dat$"x"
}

Where I could then call test(1) and get an output of [1] 1 2 3 4 5.

When I run this code now, it returns NULL with a warning message "Unknown or uninitialized column: 'x'." How can I fix this?


Solution

  • You can use [[

    test <- function(x) {
        dat[[as.character(x)]]
    }
    

    or get

    test <- function(x) {
        get(as.symbol(x), dat)
    }
    

    such that

    > test(1)
    [1] 1 2 3 4 5