使用 get() 和 paste() 赋值

Assignment using get() and paste()

在我的代码中,我必须创建一个分配一些值的对象,如下所示:

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

那我得换一些,像这样:

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

但我收到以下错误:"Error in get(paste("a", "bis", sep = "."))[1:2] <- 7:8 : target of assignment expands到非语言对象。

当然上面的代码是真实代码的简化版本。我想要做的是构建一个循环,允许我在数据框中替换某些计算的结果。像这样

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)

在这种情况下,错误表明:*get(paste(country[j], ".ext", sep = ""))$mx[(24 * i - 24 + 1) 出错: (24 * : 找不到函数 "get<-"*

提前致谢。

您最好将这些项目保存在列表中。

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

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))

这让您从 get()assign() 的痛苦中解脱出来,并且将您的数据置于循环/应用的良好结构中。