You can not do directly with assign
. As stated in the help:
Assignment does not dispatch assignment methods, so it can not be used to
set elements of vectors, names, attributes, etc.
If you want to use assign
, a workaround 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 non-recommended way to do something similar would be with eval
and parse
:
eval(parse(text = paste("teste[1]", "<-", 2)))
In all these cases, you may have a simpler solution depending on the specific problem you are dealing with.