0

In my code I have to create an object assigning some values, something like this:

assign(paste("a","bis",sep="."),rep(NA,5))

then I have to replace some of them, like this:

get(paste("a","bis",sep="."))[1:2] <- 7:8

But I get the following error: "Error in get(paste("a", "bis", sep = "."))[1:2] <- 7:8 : target of assignment expands to non-language object".

Of course the code above is a simplified version of the real one. What I'm trying to do is to build a loop which allows me to replace in a data frame the results of some calculations. Something like this

assign(paste(country[j],"ext",sep="."),
       data.frame(Year=rep(unique(get(country[j])$Year),each=24),
       Age=rep(c(0,1,seq(5,110,5)),length(unique(get(country[j])$Year))),
       mx=NA,qx=NA,lx=NA,Lx=NA,Tx=NA,ex=NA))

get(paste(country[j],".ext",sep=""))$mx[(24*i-24+1):(24*i)] <- 
    c(subset(get(country[j]),Age<=70 & Year==year)$mx,mx.ext)

in this case, the error indicates that: *Error in get(paste(country[j], ".ext", sep = ""))$mx[(24 * i - 24 + 1):(24 * : could not find function "get<-"*

Thanks in advance.

vmgarciag
  • 35
  • 4
  • rawr is teasing me a bit, because this issue is a bit of a pet peeve of mine. You've painted yourself into a bit of corner by relying so heavily on `get` and `assign`. However, it is often hard to help in these circumstances because the solution is kind of to re-engineer your entire approach, which if often beyond the scope of a single SO question. – joran Apr 13 '16 at 16:24
  • 1
    @rawr [Here](http://stackoverflow.com/a/36336614/324364) it is, I think. – joran Apr 13 '16 at 16:26

1 Answers1

2

You would be better off saving these items in a list.

myList <- list()
myList[[paste("a","bis",sep=".")]] <- rep(NA,5))

or

myList[[paste(country[j],"ext",sep=".")]] <- data.frame(Year=rep(unique(get(country[j])$Year),each=24),
                           Age=rep(c(0,1,seq(5,110,5)),length(unique(get(country[j])$Year))),
                           mx=NA,qx=NA,lx=NA,Lx=NA,Tx=NA,ex=NA))

This relieves you from the pains of get() and assign() and also puts your data in nice structure for looping / applying.

lmo
  • 37,904
  • 9
  • 56
  • 69
  • Wonderful, it works great. So main idea in this kind of problems is using a list instead of assign, right? Which is then the best use for assign and get in your opinion? – vmgarciag Apr 13 '16 at 20:35
  • @vmgarciag I would say the above method is nearly always preferable to assign. See the following post: [http://stackoverflow.com/questions/17559390/why-is-assign-bad][assign] – lmo Apr 13 '16 at 22:16
  • @vmgarciag I use `get` sometimes when I need to use a string at some point, maybe with `paste` to access some object, usually in a self-written function. Most likely this is laziness on my part that can be reworked into the above approach. – lmo Apr 13 '16 at 22:26