4

国のリストの分析を数回実行しており、各反復中に結果をベクトルに追加する必要があります。以下に、1つの国だけのループのない単純化された例を示します。徹底的に解決策を探しましたが、答えが見つかりませんでした。

#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は、機能することが保証されていません。これは、通常は使用するのが適切ではない複数の理由の1つです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 に答える