0

I have a data frame and need to extract a column based on a column name. I don't know in advance what the headers will be called, but an object I have will know.

So let's say the dataframe is called target_data, and it has a field called Treatment_Time. So usually I would access this by, target_data$Treatment_Time and things would be fine. In this case, I have a string variable containing, "Treatment_Time". Let's say myField <- "Treatment_Time".

I want to access target_data$Time by using the myField variable.

I have looked elsewhere and have tried the following:

> test <- paste("target_data", "$", my_field, sep="")
> test
  [1] "target_data$Treatment_Time"

> eval(test)
  [1] "target_data$Treatment_Time"

> eval(as.name(test))
  Error in eval(as.name(test)) : 
    object 'target_data$Treatment_Time' not found

> eval(as.symbol(test))
  Error in eval(as.name(test)) : 
    object 'target_data$Treatment_Time' not found

> eval(parse(test))
    Error in file(filename, "r") : cannot open the connection
    In addition: Warning message:
    In file(filename, "r") :
      cannot open file 'target_data$Treatment_Time': No such file or 
      directory

> get(test)
    Error in get(test) : object 'target_data$Treatment_Time' not found

> get("target_data")$test
    NULL

So the shotgun method isn't working this time. Does anyone know how to do this? Thanks!

Adam Price
  • 810
  • 2
  • 11
  • 21

0 Answers0