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