1
my.function <- function(df,col){
    t <- df$col
    return(t)
}

This is the code I've written up to subset a column in a dataframe, but it returns NULL, when I attempt this. I don't understand what's wrong. Please help!

Moosa ali
  • 13
  • 2

1 Answers1

1

We need to use [[ instead of $, otherwise, it will be checking the name of the 'col' as col literally instead of the value - i.e. kind of an associative array. Therefore, when it checks for the column named 'col' and not present, it returns NULL

iris$col
#NULL

So, here, we change the $ to [[ and run the iris example data

my.function <- function(df, col){
   t <- df[[col]]
    return(t)
   }

my.function(iris, "Species")
my.function(iris, 5)
akrun
  • 874,273
  • 37
  • 540
  • 662