Assignment using get() and paste()

大憨熊 提交于 2021-02-11 16:57:01

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/36604166/assignment-using-get-and-paste

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!