【问题标题】:Assigning Values within a dynamically named matrix in R在 R 中的动态命名矩阵中赋值
【发布时间】:2015-03-13 21:11:25
【问题描述】:

我在 R 中的一个循环中苦苦挣扎,我必须使用动态变量名(我被告知这是其他关于动态变量名的帖子的坏主意,但我很确定我需要基于我的文件结构体)。循环进入的每个文件夹都有不同数量的文件。

动态变量名称包含矩阵,我需要查看矩阵的每一行/列并输出一个新矩阵。

简化示例:

 var 1 is a matrix(0,40,40) 
 var 2 is a matrix(0,45,45) 
 var 3 is a matrix(0,40,40) 

For (f in 1:(length of var3s))  # the number of files in the folder, in each folder: 

For (g in 1: ncol(var1)) {  
  For (h in 1: nrow(var1)) {
    if (var 1[g,h]>4 & var 2[g,h]<1)
          { var3[f] [g,h]<-1}    # <- you cannot do this, but this is ultimately what I want 
}
}

我想从变量 3 的列表中取出第 f 个变量矩阵,并为 [g,h] 的位置赋值 我以前用真正的变量名做过这个,但我在添加动态元素时很吃力。这就是它的样子和我得到的错误。

for (f in 1:(length(LD139_040))){
  assign(paste0("LD139_040s",f),
  matrix(0,nrow(eval(parse(text=paste0("B139_040",f)))),
  ncol(eval(parse(text=paste0("B139_040",f)))))) # this effectively creates my new matrix (var3 above) the size I need based on the files above

for (g in 1:(ncol(eval(parse(text=paste0("B139_040",f)))))){
  for (h in 1:(nrow(eval(parse(text=paste0("B139_040",f)))))){
  if (S139_040[g,h]>10 & 
  (assign(paste0("LD139_040",f), as.matrix(raster(LD139_040[f]))))[g,h]>.295 & 
  (assign(paste0("LD139_040",f), as.matrix(raster(LD139_040[f]))))[g,h]<.33 &  
  (assign(paste0("B139_040",f), as.matrix(raster(Blue139_040[f]))))[g,h]<180) 
    # this section also works and will give me a t/f at each location [g,h]
    # if true, assign the value 1 to the new matrix LD139_040 at f
  {assign(paste0("LD139_040s", f)[g,h], 1)}

   }
  }
}

我尝试了 eval 和 assign 的各种组合来组织最后一条语句,但我得到了诸如“无效的第一个赋值”、不正确的维数和赋值目标扩展到非语言对象等错误。

感谢您的帮助!

R 版本 3.1.1 “Sock it to Me”与库(光栅)

【问题讨论】:

    标签: r dynamic eval assign r-raster


    【解决方案1】:

    这不需要动态变量名称。在循环内的每次迭代中,所有名称都将同时更改。

    例如,我是这样回答代码块 2 中的部分的:

    for (f in 1:(length(LD139_040))){
        currenttile<-LD139_040[f]
        Blue<-B139_040[f]
        newmatrix<- matrix(0,nrow(Blue),ncol(Blue))
        for (g in 1:(ncol(B139_040[f]))){
          for (h in 1:(nrow(B139_040[f]{
           if (S139_040[g,h]>10 & currenttile[g,h]>.295 & currenttile[g,h]<.33 & Blue [g,h]<180)
           {newmatrix[g,h]<-1}
         }
        }
       }
    

    更简单地说,因为我了解到只要矩阵的维度相同,您就不必遍历每个位置:

    for (f in 1:(length(LD139_040))){
        currenttile<-LD139_040[f]
        Blue<-B139_040[f]
        newmatrix<- matrix(0,nrow(Blue),ncol(Blue))
        currenttile[currenttile >.295 & currenttile <.33]<- 1
        Blue[Blue<180]<- 1
        newmatrix[Blue==1 & currenttile==1]<- 1 
       }
    

    因此,感谢所有试图破译此问题的人,这对我来说是一个令人困惑的问题,因为我花了一段时间才弄清楚如何最好地解决它,(显然是如何解释它)。我希望这对某人有帮助!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-24
      • 2017-03-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多