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

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.

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

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
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