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