Given this:
vec1 = 1:10
varname = "vec1"
I know I can do this:
eval(parse(text=paste0(varname,"[5] = 20")))
I want to find something cleaner if possible. I tried this:
`<-`(`[`(as.name(varname), 5), 20)
But I get an error: "object of type 'symbol' is not subsettable".
Something very similar does work:
`<-`(`[`(vec1, 5), 20)
Why is vec1
being treated differently from as.name("vec1")
when passed as the first argument to the [
function?
If I try this:
`<-`(`[`(as.name("vec1"), 5), 20)
I get a curiously different error: "target of assignment expands to non-language object".
Can someone explain the nuances involved here? And are there cleaner ways to do what I want, while keeping vec1 as a simple, standalone, top-level variable? The actual scenario in this case is more involved and I already have a workaround; I'm asking this more to understand the fundamentals of what's possible and what's not possible with R.