動的変数名を使用する必要がある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" with library(raster)