R - 粘贴命令以调用矩阵名称
R - Paste command to call a matrix name
我有一个特定国家/地区的以下命令,这里是 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))])}
由于某些原因,粘贴命令只是调用了矩阵的名称,并没有将其识别为代码最后一行中的矩阵。提前谢谢大家!
不要(永远)使用 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.
}
我有一个特定国家/地区的以下命令,这里是 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))])}
由于某些原因,粘贴命令只是调用了矩阵的名称,并没有将其识别为代码最后一行中的矩阵。提前谢谢大家!
不要(永远)使用 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.
}