2

I am aware of selecting a column of data frame using data$column. My question - Is there a way to do that dynamically where I create a function and pass data, columnName as parameter and get the result back

fnGetColumnData (data, columnName) {
   data$columnName
}

above does not work when encapsulating the code in a function. However if I write data$"columnName" then it works. Is there a way to encapsulate this?

acylam
  • 18,231
  • 5
  • 36
  • 45
Ankit
  • 6,388
  • 8
  • 54
  • 79

2 Answers2

2

Try this:

select_col<-function(df,colname){
 colname<-deparse(substitute(colname))
  df[colname]
}
select_col(iris,Species)
NelsonGon
  • 13,015
  • 7
  • 27
  • 57
1

With dplyr and rlang:

library(dplyr)
library(rlang)

fnGetColumnData = function(data, columnName){
  colname_quo = enquo(columnName)
  pull(data, !!colname_quo)
}

Output:

> fnGetColumnData(mtcars, "cyl")
 [1] 6 6 4 6 8 6 8 4 4 6 6 8 8 8 8 8 8 4 4 4 4 8 8 8 8 4 4 4 8 6 8 4

> fnGetColumnData(mtcars, cyl)
 [1] 6 6 4 6 8 6 8 4 4 6 6 8 8 8 8 8 8 4 4 4 4 8 8 8 8 4 4 4 8 6 8 4
acylam
  • 18,231
  • 5
  • 36
  • 45