0

I have a question I have a dataframe df which I take from here as example

emp.data <- data.frame(
   emp_id = c (1:5), 
   emp_name = c("Rick","Dan","Michelle","Ryan","Gary"),
   salary = c(623.3,515.2,611.0,729.0,843.25), 
   
   start_date = as.Date(c("2012-01-01", "2013-09-23", "2014-11-15", "2014-05-11",
      "2015-03-27")),
   stringsAsFactors = FALSE
)


 emp_id emp_name salary start_date
1      1     Rick 623.30 2012-01-01
2      2      Dan 515.20 2013-09-23
3      3 Michelle 611.00 2014-11-15
4      4     Ryan 729.00 2014-05-11
5      5     Gary 843.25 2015-03-27

I want to call emp.data$emp_name However I want a different approach.

text = "emp_name"

emp_id$paste(text)

It is because I create a function that can pass the input string as the symbol to call the column or doing filter, for now !!sym(text) from rlang works for doing something like filter.

emp.data %>% filter(!!sym(text) == "Rick")

How to make it works in one go? Thanks

Trojan666
  • 87
  • 7

1 Answers1

0

You may use the double bracket list notation here:

text <- "emp_name"
emp.data[[text]]

[1] "Rick"     "Dan"      "Michelle" "Ryan"     "Gary"

Note that data frames are special types of list, so most of the list syntax also works with them.

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360