2
get_column <- function(df, feature) {
      return(df$feature)
}

get_column(mtcars, "mpg")
## NULL

When I put a dataframe into an argument of the above function and try to return a column from it. I get NULL as the result. Why is this the case and how can I properly perform this task?

Eisen
  • 1,697
  • 9
  • 27

1 Answers1

1

We can use [[ instead of $. Also, return wrapping is not really needed in R. According to ?return

If the end of a function is reached without calling return, the value of the last evaluated expression is returned.

get_column <- function(df, feature) {
     return(df[[feature]])
   }
akrun
  • 874,273
  • 37
  • 540
  • 662
  • Why does the `$` not work here? And how does it know what to return without a return wrapping? – Eisen Jun 12 '20 at 21:05
  • @Elsen Updated the post. With the `$`, it is doing a literal evaluation for 'feature' instead of the value passed with feature. So, it i looking for `df$feature` of `df$mpg` – akrun Jun 12 '20 at 21:07