我正在多次运行国家/地区列表的分析,并且在每次迭代期间,结果应该添加到向量中。下面我展示了一个简化的例子,没有一个国家的循环。即使我彻底寻找解决方案,我也找不到答案。
#this is my simplified country vector with just 1 country
country<-c("Spain")
#This is the vector that should hold the results of multiple iterations
#for now, it contains only the result of the first iteration
Spain.condition1<- 10
#reading result vector in a variable (this is automized in a loop in my code)
resultVector<-paste(country,"condition1",sep=".")
#when I call the content of the vector with parse, eval
#I see the content of the vector as expected
eval(parse(text=resultVector))
#however, when I try to add a second result to it
eval(parse(text=resultVector))[2]<-2
#I get following error message:
#Error in file(filename, "r") : cannot open the connection
#In addition: Warning message:
#In file(filename, "r") :
# cannot open file 'Spain.condition1': No such file or directory
有人可以帮助我或让我朝着正确的方向前进吗?
答案 0 :(得分:2)
无法保证分配给eval
。这是使用eval
通常不是一个好主意的多种原因之一。
为什么不将国家及其条件存储在命名列表中,如下所示:
conditions = list()
conditions[["Spain"]] = list()
conditions[["Spain"]][["condition1"]] <- 10
conditions[["Spain"]][["condition1"]][2] <- 2
conditions[["Spain"]][["condition1"]]
# [1] 10 2
ETA:使用循环(我不确切知道你的问题的结构是什么,但这是一般的想法):
countries = c("Spain", "England", "France", "Germany", "USA") # and so on
conditions = c("Sunny", "Rainy", "Snowing") # or something
data = list()
for (country in countries) {
data[[country]] <- list()
for (condition in conditions) {
data[[country]][[condition]] <- 4 # assign appropriate value here
}
}
它也可以用制表符分隔的文件构建,或者以适合你的问题的任何方式生成--R超出能力。
答案 1 :(得分:2)
大卫的解决方案要好得多,但你可以使用get和assign来做到这一点。
country <- "Spain"
Spain.condition1 <- 10
resultVector <- paste(country, "condition1", sep=".")
eval(parse(text=resultVector))
#[1] 10
# Now this is one way to modify that object
# Note that we *need* to assign to a temporary object
# and just using get(resultVector)[2] <- 2 won't work
tmp <- get(resultVector)
tmp[2] <- 2
assign(resultVector, tmp)
Spain.condition1
#[1] 10 2
# We could alternatively do this with eval
# Even if it is a bad idea
eval(parse(text = paste0(resultVector, "[2] <- 3")))
Spain.condition1
#[1] 10 3