0

Can someone give me some insight into why this piece of code is not working?

tr <- function(x,y,z){eval(as.symbol(paste0(x,y,z)))}

sr <- c("bla","gla")
blablabla <- as.numeric()

tr("bla",sr[1],"bla")[1] <- 1

I define a function tr which pastes three strings and turns it into a variable vector. I then try to change the first element of that vector into 1, however I keep running into the error:

Error in tr("bla", sr[1], "bla")[1] <- 1 : target of assignment expands to non-language object

alki
  • 3,044
  • 5
  • 19
  • 43

2 Answers2

1

Reason for the error.

as.symbol(paste0(x,y,z)) creates a symbol from your pasted string.

eval(as.symbol(paste0(x,y,z)) then evaluates the value of that symbol. So at the minute you have created a variable called 'blablabla' with nothing in. You're then evaluating it to give numeric(0).

You then return numeric(0) and try to assign a value to it giving you the error.

Solution to Error

I won't put in the checks and things, but lets say you created a variable called blablabla and assign the value as 1 (blablabla <- 1). This prevents the previous error occurring. Then use the code:

tr <- function(x,y,z, index, value){
    var_temp <- eval(as.symbol(paste0(x,y,z)))
    var_temp[index] <- value
    return(var_temp)
}

To assign values to different values in the vector depending on the index and value arguments. You'll have to assign the output to something as well, because blablabla will only be changed within the scope of the function, so it would be used: blablabla <- tr("bla", "bla", "bla", 1, 2) to set the first element to two.

Does that answer the question?

JCollerton
  • 3,074
  • 2
  • 19
  • 23
  • Thanks for the answer. I'm actually not trying to create a variable called blablabla but want to be able to assign values to a variable vector. So for example I want to be able to assign `blablabla[2] – alki Aug 14 '15 at 10:39
1

To my knowledge, R only lets you do an assignment to a variable "name".

I guess your code would work if you do this instead:

A <- tr("bla",sr[1],"bla")

A[1] <- 1

Hope this helps.