Reputation: 53
I have the following commands for one specified country, here AT and I would like to do it for more.
c1<-grep(pattern="AT",x=names(climatebig3),value=TRUE)
c1matAT<-climatebig3[c1]
c1matAT<-c1matAT[,which(apply(!is.na(c1matAT[1:27,]),2,all))]
Taking a vector of countries and looping it over the first two commands works, but not for the third one.
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))])}
For some reason, the paste command just invokes the name of the matrix and does not recognize it as a matrix in the last line of the code. Thank you all in advance!
Upvotes: 0
Views: 355
Reputation: 173577
Don't (ever) use assign
. Use lists instead:
#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.
}
Upvotes: 2