I'm trying to use the get function in R to reference and return a column in a data frame.
Taking this example data frame:
x <- data.frame(id= c("a", "b", "c"), term= c(179, 182, 179), col1= c(1, 2, 3), col2 = c(4, 5, 6))
Now, let's say I put the 2 column variable names into a vector
vars <- c("x$col1", "x$col2")
Then when I call get on vars, I want it to return the appropriate values, e.g. get(vars[2]) should ideally return x$col2.
However I get the following error when I try running get(vars[2])
> get(vars[2])
Error in get(vars[2]) : object 'x$col2' not found
But when I just run x$col2 there is no issue and I get the expected result:
> x$col2
[1] 4 5 6
So clearly the object x$col2 exists.
What am I doing wrong here?