Vote count:
0
I am struggling with a loop in R where I have to use dynamic variable names (which I am told is a bad idea from the other posts about dynamic variable names, but I am pretty sure that I need to based on my file structure). Each folder for which the loop enters, there is a different number of files.
The dynamic variable names contain matrices and I need to look in each row/column of the matrix and output a new matrix.
Streamlined example: var 1 is a 40x40 matrix var 2 is a 45x45 matrix var 3 is a 40x40 matrix
for (f in 1:(length of var3s)) # the number of files in the folder, in each folder do:
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
}
}
I want to take the f-th variable matrix from variable 3's list and assign a value to the location at [g,h] I've done this before with real variable names, but I am struggling with adding the dynamic element. This is what it looks like and the errors I'm getting.
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)}
}
}
}
I have tried a variety of combinations of eval and assign to organize the last statement, and I get errors such as 'invalid first assignment', incorrect number of dimensions, and target of assignment expands to non-language object.
Thanks for your help!
R version 3.1.1 "Sock it to Me" with library(raster)
Assigning Values within a dynamically named matrix in R
Aucun commentaire:
Enregistrer un commentaire