You can’t do it directly with the assign
. As stated in the aid:
assign does not Dispatch assignment methods, so it cannot be used to
set Elements of Vectors, Names, Attributes, etc.
If you want to use the assign
, a solution would be to make a temporary copy before:
temp <- get("teste")
temp[1] <- 2
assign("teste", temp)
teste
[1] 2 2 3 4 5
You could create a function that does this:
assign2 <- function(x, i, value){
temp <- get(x, envir = parent.frame())
temp[i] <- value
assign(x, temp, envir = parent.frame())
}
x <- "teste"
assign(x, 1:5)
teste
[1] 1 2 3 4 5
assign2(x, 1, 2)
teste
[1] 2 2 3 4 5
Another unwelcome way to do something similar would be with eval
and parse
:
eval(parse(text = paste("teste[1]", "<-", 2)))
In all these cases, you are likely to have a simpler solution depending on the specific problem you are dealing with.
Carlos, why is this form not recommended?
– Guilherme Duarte
@Guilhermeduarte has a look here http://stackoverflow.com/questions/13649979/what-specifically-are-the-dangers-of-evalparse
– Carlos Cinelli