Is it possible to modify a value of a vector with assign () in R?

2

Suppose we have

x <- "teste"

You can assign another string to the test, using assign:

assign(x, 1:5)

So:

  

test

     

[1] 1 2 3 4 5

Would it be possible for me to modify any of the vector values using assign? Something like:

assign("teste[1]", 2)
    
asked by anonymous 09.01.2015 / 01:04

1 answer

2

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.

    
09.01.2015 / 01:52