I want to be able to change the cell of a dataframe by referring to the object's name, rather than to the object itself, but when I attempt do do so it results in the warning could not find function "eval<-"
.
I can change a cell of a standard dataframe using the code below:
my_object = tibble(x = c("Hello", "Goodbye"),
y = c(1,2))
object[2,1] <- "Bye"
But I am having trouble doing the same when using the object's name. I can evaluate the object using its name and extract the relevant cell:
object_name = "my_object"
eval(sym(object_name))[2, 1]
But I can't assign a new variable to the object (error: could not find function "eval<-"
):
eval(sym(object_name))[2, 1] <- "Bye"
CodePudding user response:
You can use get()
instead of eval(sym())
to obtain an object by name. You can also use the [<-
function to write a value to it without requiring an intermediate copy:
my_object = dplyr::tibble(x = c("Hello", "Goodbye"),
y = c(1,2))
object_name = "my_object"
`[<-`(get(object_name), 2, 1, value ="Bye")
#> # A tibble: 2 x 2
#> x y
#> <chr> <dbl>
#> 1 Hello 1
#> 2 Bye 2
Created on 2022-06-02 by the reprex package (v2.0.1)
CodePudding user response:
If you want to define your command as a string, parse it as an expression, and then use eval:
eval(parse(text=paste0(object_name,"[2,1]<-'Bye'")))
> object
x y
1 Hello 1
2 Bye 2