[英]Assigning Values within a dynamically named matrix in R
我在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”(光柵)
這不需要動態變量名。 在循環內的每次迭代中,所有名稱都將同時更改。
例如,這就是我回答代碼塊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
}
因此,感謝嘗試破譯的每個人,這對我來說是一個令人困惑的問題,因為花了一段時間才弄清楚如何最好地進行處理(以及顯然如何進行解釋)。 我希望這可以幫助別人!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.