0

我在 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”与库(光栅)

4

1 回答 1

0

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

例如,我是这样回答代码块 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 
   }

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

于 2015-06-05T03:24:04.260 回答