4

我正在多次对国家列表进行分析,并且在每次迭代期间,应将结果添加到向量中。下面我展示了一个简化的例子,没有一个国家的循环。即使我彻底寻找解决方案,我也找不到答案。

#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

任何人都可以帮助我或让我朝着正确的方向前进吗?

4

2 回答 2

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 功能强大。

于 2012-05-16T02:45:10.763 回答
2

David 的解决方案要好得多,但您可以使用 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
于 2012-05-16T02:59:05.553 回答