使用get()和paste()进行赋值 [英] Assignment using get() and paste()
问题描述
在我的代码中,我必须创建一个分配一些值的对象,如下所示:
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
但是我收到以下错误:"get(paste("a","bis",sep =."))中的错误[1:2]<-7:8:赋值目标扩展为non-语言对象".
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)
在这种情况下,错误指示:* get(paste(country [j],".ext",sep ="))$ mx [(24 * i-24 +1):( 24*:找不到函数"get<-" *
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<-"*
谢谢.
推荐答案
最好将这些项目保存在列表中.
You would be better off saving these items in a list.
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()
的烦恼,并且使您的数据具有良好的循环/应用结构.
This relieves you from the pains of get()
and assign()
and also puts your data in nice structure for looping / applying.
这篇关于使用get()和paste()进行赋值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!