使用 for 循环保存数据矩阵?

Using for loops to save a matrix of data?

我正在尝试查找风数据的概率密度函数。下面是我如何根据平均风速计算比例参数。

k<-2
for(i in 1:length(Windmean)){
      Scale[i]=as.numeric(Windmean[i]/(exp(gammaln(1+(1/k)))))
      }

> Scale
 [1] 3.913934 3.996000 4.012884 3.925220 3.856707 3.849608 3.820578 3.943110 3.945975 3.842338 3.891791
[12] 3.933083 3.993944 3.907775 3.847120 3.853263 3.917156 4.028956 3.878879 3.753880 3.969074 3.818923
[23] 3.855913 3.993075 3.985828 3.914240 3.854336 3.620460 3.848180 3.843788 3.830617 3.841890 3.879547
[34] 3.904059

如果这些是我的比例参数结果,我想使用下面的公式来获得风概率 Wind_prob. 我会。

Scale<- cbind(3.913934,3.996000,4.012884,3.925220,3.856707,3.849608,
3.820578,3.943110,3.945975,3.842338,3.891791,3.933083,3.993944,3.907775,
3.847120,3.853263,3.917156,4.028956,3.878879,3.753880,3.969074,3.818923,
3.855913,3.993075,3.985828,3.914240,3.854336,3.620460,3.848180,3.843788,
3.830617,3.841890,3.879547,3.904059)  ##Length 34

bins<-cbind(seq(0.5,25,by=0.5)) ##Length 51
                      bins<-cbind(bins)
        shape<-k
                for(i in 1:length(bins)){
for(o in 1:length(Scale)){
                Wind_prob[i]<-(0.5*(exp(-1*(bins[i,1]/shape)^shape))*(shape/as.numeric(Scale[o]))*((bins[i,1]/as.numeric(Scale[o]))^(shape-1)))
            }
}

我得到了 51 个概率函数的列表 (i=34),但我应该得到 [51*34] 的矩阵。基本上,我想为每 34 个比例函数获得 51 个概率函数。看来我的迭代没有保存在矩阵中。我也在 wind_prob 中尝试了 as.matrixas.array,但无法正常工作。 有人可以指出我需要在代码中进行的更改吗?谢谢。

您需要使用矩阵:

Scale <- c(3.913934,3.996000,4.012884,3.925220,3.856707,3.849608,
           3.820578,3.943110,3.945975,3.842338,3.891791,3.933083,3.993944,3.907775,
           3.847120,3.853263,3.917156,4.028956,3.878879,3.753880,3.969074,3.818923,
           3.855913,3.993075,3.985828,3.914240,3.854336,3.620460,3.848180,3.843788,
           3.830617,3.841890,3.879547,3.904059)  ##Length 34
bins <- seq(0.5, 25, by = 0.5) # length 50
shape <- 2
Wind_prob <- matrix(NA_real_, length(bins), length(Scale))
for (j in seq_along(Scale)) {
  for (i in seq_along(bins)) {
    Wind_prob[i, j]<-(0.5*(exp(-1*(bins[i]/shape)^shape))*
                        (shape/as.numeric(Scale[j]))*
                        ((bins[i]/as.numeric(Scale[j]))^(shape-1)))
  }
}