Ankit
Ankit

Reputation: 6664

R select column of data frame by name

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?

Upvotes: 2

Views: 85

Answers (2)

NelsonGon
NelsonGon

Reputation: 13319

Try this:

select_col<-function(df,colname){
 colname<-deparse(substitute(colname))
  df[colname]
}
select_col(iris,Species)

Upvotes: 2

acylam
acylam

Reputation: 18701

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

Upvotes: 1

Related Questions