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,334
  • 5
  • 22
  • 45
  • 1
    You get the same simply with `mean(1:5)[1] <- 1`. –  Aug 14 '15 at 09:56
  • Sorry I don't understand, could you explain it to me a little more? – alki Aug 14 '15 at 10:01
  • I mean, your function is not an exception. It is easy to reproduce the same behavior using `mean`, for example. It shows that what you are trying to do is not allowed. –  Aug 14 '15 at 10:02
  • Which part of my code is making the operation illegal? – alki Aug 14 '15 at 10:12
  • `tr("bla",sr[1],"bla")[1] <- 1`, `mean(1:5)[1] <- 1`, `sd(1:5)[1] <- 1`, `min(1:5)[1] <- 1`, `max(1:5)[1] <- 1` and so on. –  Aug 14 '15 at 10:14
  • 1
    `tr` seems like an unnecessary function; why not just use `paste0`? – sdgfsdh Aug 14 '15 at 10:45

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,227
  • 2
  • 20
  • 25
  • 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] <- 2` or `blaglabla[2] <- 2` just by changing the number in the brackets: `tr("bla",sr[1],"bla")` or `tr("bla",sr[2],"bla")` – 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.