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

Asked

Viewed 222 times

2

Suppose we have

x <- "teste"

You can assign another string to test using assign:

assign(x, 1:5)

Thus:

test

[1] 1 2 3 4 5

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

assign("teste[1]", 2)

1 answer

2


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?

  • 1

    @Guilhermeduarte has a look here http://stackoverflow.com/questions/13649979/what-specifically-are-the-dangers-of-evalparse

Browser other questions tagged

You are not signed in. Login or sign up in order to post.