对于一个指定的国家/地区,我在AT处具有以下命令,我想在更多国家使用它。
c1<-grep(pattern="AT",x=names(climatebig3),value=TRUE)
c1matAT<-climatebig3[c1]
c1matAT<-c1matAT[,which(apply(!is.na(c1matAT[1:27,]),2,all))]
获取国家/地区向量并将其循环到前两个命令中有效,但不适用于第三个命令。
countries<-c("AT","BE","BG","CZ","DK","DE","EE","IE","EL","ES","FR","HR","IT","CY","LV","LT","LU","HU","MT","NL","PL","PT","RO","SI","SK","FI","SE","UK")
for (i in 1:28){assign(paste("c1mat",as.character(countries[[i]]),sep=""),climatebig3[,grep(pattern=as.character(countries[[i]]),x=names(climatebig3),value=TRUE)])
assign(paste("c1mat",as.character(countries[[i]]),sep="", paste("c1mat",as.character(countries[[i]]),sep="")[,which(apply(!is.na(as.character(paste("c1mat",as.character(countries[[i]]),sep=""))[1:27,]),2,all))])}
由于某种原因,paste命令仅调用矩阵的名称,而在代码的最后一行中将其识别为矩阵。预先谢谢大家!
答案 0 :(得分:1)
永远不要使用assign
。改用列表:
#Create an empty named list the same length as the number of countries
c1mat_list <- setNames(vector("list",length(countires)),countries)
#Loop through countries and populate the list
for (x in countries){
c1 <- grep(pattern= x,x=names(climatebig3),value=TRUE)
c1mat_list[[x]] <-climatebig3[c1]
#etc.
}