R - 粘贴命令以调用矩阵名称

问题描述 投票:0回答:1

我有一个指定国家的以下命令,在这里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命令只调用矩阵的名称,并且不会将其识别为代码最后一行中的矩阵。谢谢大家!

r string loops paste assign
1个回答
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.
}
© www.soinside.com 2019 - 2024. All rights reserved.