簡體   English   中英

用函數輸出R填充矩陣

[英]Fill matrix with function output R

我正在嘗試在矩陣的每個實例處用函數的輸出填充矩陣。 我收到錯誤消息“替換的長度為零”或“要替換的項目數不是替換長度的倍數”。

請幫忙!

setPoint <- function(tarray, t){
    var1 <- dim(tarray)[1] #get the length of longitudes, returns a number
    var2 <- dim(tarray)[2] #get the length of latitudes, returns a number
    empty.matrix <- matrix(nrow=var1,ncol=var2)
    for (i in 1:var1) { #i is moving from 1 to 192 (longitude)
        for (j in 1:var2) { #j moves from 1 to 145 (latitude) 
            tmp.point <- tarray[i,j,]
            1my.vector <- c(1:var2)
            my.vector[j] <- thresholdYear(tmp.point, 38,t,0.8)
        }
        empty.matrix[i,] <- my.vector
    }

}

首先,您的函數不返回任何內容。 R中的for循環返回NULL ,這就是您的函數返回的結果。 其次,在內部循環中,創建my.vector並在下一條指令中重寫其值之一。 循環的第二次迭代將重新創建它,因此破壞了先前迭代的值,依此類推。在我看來,您需要做的是在內部循環之外創建它。 類似於以下內容。

setPoint <- function(tarray, t){
var1 <- dim(tarray)[1] #get the length of longitudes, returns a number
var2 <- dim(tarray)[2] #get the length of latitudes, returns a number
empty.matrix <- matrix(nrow=var1,ncol=var2)
for (i in 1:var1) { #i is moving from 1 to 192 (longitude)
      my.vector <- 1:var2
    for (j in 1:var2) { #j moves from 1 to 145 (latitude) 
        tmp.point <- tarray[i,j,]
        my.vector[j] <- thresholdYear(tmp.point, 38,t,0.8)
    }
    empty.matrix[i,] <- my.vector
}
empty.matrix

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM