我试图在R中创建一堆带有循环的向量,如下所示:
dlist <- c('"lnincome", "retprice", "age15to24"',
'"retprice", "age15to24", "beer"',
'"retprice", "age15to24"',
'"retprice", "beer"',
'"lnincome", "beer"')
for (i in 1:length(dlist)) {
output_[[i]]<-dataprep(foo = smoking,
predictors = c(cat(dlist[i])),
predictors.op = c("mean"),
special.predictors = list(
list("cigsale", 1988, "mean"),
list("cigsale", 1980, "mean"),
list("cigsale", 1975, "mean")
),
dependent = c("cigsale"),
unit.variable = "statenum",
time.variable = c("year"),
treatment.identifier = 3,
controls.identifier = c(1:2, 4:39),
time.predictors.prior = c(1980:1988),
time.optimize.ssr = c(1975:1988),
time.plot = c(1975:2000),
unit.names.variable = c("state")
)
#assign( paste("test_", eval(i), sep="") , output)
synth.out_[[i]]<-synth(output_i)
#assign( paste("synth_", eval(i), sep="") , synth.out)
path.plot(dataprep.res = output_i, synth.res = snyth.out_i)
rm(synth.out, test)
}
然而,当循环运行时,我收到的错误是&#34; object&#39; test _&#39;未找到。如何创建对象test_1是在循环的第一次迭代,然后是对象test_2,直到test_n(n = 5,这里)。
然后,如何在path.plot函数中调用output_i和synth_i的创建值?
提前致谢!
答案 0 :(得分:0)
您正在寻找的是函数get()
如
get(paste("output_", i, sep=""))
我通常会建议你不要制作这么多变量,而是将它们放在一个命名列表中。为此,您可以更新以下内容。
output_ <- list()
synth.out_ <- list()
for (item in dlist) {
output_[paste(item)]<-dataprep(foo = smoking,
predictors = c(cat(dlist[i])),
predictors.op = c("mean"),
special.predictors = list(
list("cigsale", 1988, "mean"),
list("cigsale", 1980, "mean"),
list("cigsale", 1975, "mean")
),
dependent = c("cigsale"),
unit.variable = "statenum",
time.variable = c("year"),
treatment.identifier = 3,
controls.identifier = c(1:2, 4:39),
time.predictors.prior = c(1980:1988),
time.optimize.ssr = c(1975:1988),
time.plot = c(1975:2000),
unit.names.variable = c("state")
)
synth.out_[paste(item)]<-synth(output[paste(item)])
path.plot(dataprep.res = output[paste(item)], synth.res = synth.out_[paste(item)])
# not sure what the last line is doing
rm(synth.out, test)
你没有给出足够的信息来试试:dataprep()
是什么,test
是什么? PS曲线函数snyth.out_i
上有拼写错误。