Can a string of the form below be evaluated so that it is equivalent to the same "literal" expression?
Example data and code:
df.name = data.frame(col1 = 1:5, col2 = LETTERS[seq(1:5)], col3 = letters[seq(1:5)], stringsAsFactors = FALSE)
col.name = "col2"
row.num = "4"
var1 = str_c("df.name$", col.name,"[",row.num,"]")
> var1
[1] "df.name$col2[4]"
The literal works as expected
> df.name$col2[4]
[1] D
get() is not equivalent:
get(var1)
## Error in get(var1) : object 'df.name$col2[4]' not found
This form of get() "works" but does not solve the problem
get("df.name")$col2[4]
[1] D
Per other posts I've tried eval(parse()) and eval(parse(text())) without success.
I'm trying to create a function that will search (subset) df.name using the col.name passed to the function. I want to avoid writing a separate function for each column name, though that will work since I can code df.name$col2[row.num] as a "literal".
EDIT
The example code should have shown the row.num as type numeric / integer, i.e., row.num = 4
df.name[[col.name]][as.numeric(row.num)]is a possibility for you. But I think you should ask yourself how you ended up with a character representation of a row number and start there.eval(parse(text=var1))should work (it works for me). But @RichScriven's solution (but withget(df.name)instead ofdf.name) should work.