0

I have a data frame called outcome1 with only one column called "pneumonia" using

outcome1 <- data.frame(Pneumonia = sample(0:1, size = 5, replace = TRUE))

I create a function called best1 that just prints that column using an argument called "var_"

best1 <- function(var_) {
  outcome1$var_
}

when I call the function

 best1("Pneumonia")

I get a NULL value

but when I use:

outcome1$Pneumonia

I get the data I need. How can I use the best1 function and get the right results using the column name as an argument, also what would be the case if the column would have a space in the name I know that you use the "``" in that case, what would be the case in using it in a function, thanks for the help

Juan Lozano
  • 635
  • 1
  • 6
  • 17

1 Answers1

2

There is a better way to write your function.

best1 <- function(var_) {
  outcome1[[var_]]
}

See ?$ for valid inputs for using that operator. Your function is looking for the variable name "var_", not the string bound to that name.

JMT2080AD
  • 1,049
  • 8
  • 15