【问题标题】:R - Paste command to call a matrix nameR - 粘贴命令以调用矩阵名称
【发布时间】:2019-07-28 14:54:30
【问题描述】:

我对一个指定的国家/地区有以下命令,这里是 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))])}

由于某种原因,粘贴命令只是调用了矩阵的名称,并没有将其识别为代码最后一行中的矩阵。提前谢谢大家!

【问题讨论】:

    标签: r string loops paste assign


    【解决方案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.
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-05-02
      • 2015-04-22
      • 2019-04-10
      • 2011-12-23
      • 2018-03-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多