使用函数输出 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

}

最新更新