0

我在代码中返回矩阵列表时遇到问题。我计算了一些矩阵,然后我需要返回所有这些矩阵。我的代码是这样的:

extractCov <- function(dataset, n) {
nolabel = dataset[1:ncol(dataset)-1]
covs <- vector(mode="list", length=n)
for(i in 1:n-1){
    covs[[i]] = cov(nolabel[min(which(dataset[ncol(dataset)]==i)):max(which(dataset[ncol(dataset)]==i)),])
}

return(covs)
}

先感谢您

编辑:错误是:

Error in covs[[i]] = cov(nolabel[min(which(dataset[ncol(dataset)] == i)):max(which(dataset[ncol(dataset)] ==  : 
  attempt to select less than one element

Edit2:输入函数:extractCov(dataset, 4)

输出:这将是这个矩阵的列表:

            V1          V2
V1  0.53272418 -0.05904113
V2 -0.05904113  0.08896365
            V1          V2
V1  0.25257629 -0.03551607
V2 -0.03551607  0.09344723
           V1         V2
V1  0.3126369 -0.1143688
V2 -0.1143688  1.0136749
           V1         V2
V1  0.4980492 -0.3421363
V2 -0.3421363  0.6674106

如果我在代码中打印,我可以得到矩阵,但我需要它在一个变量中。

数据集:

7.61353 5.36408 0
6.4567 6.15247 0
6.91345 5.43851 0
6.25107 5.93832 0
5.31617 5.48388 0
6.44819 5.78016 0
6.71252 5.45722 0
6.00962 5.87266 0
6.51371 5.82471 0
7.13969 5.81655 0
7.89513 5.86599 0
5.83555 6.34041 0
7.28842 -2.63489 1
7.24215 -2.73484 1
6.02468 -2.33083 1
5.9257 -2.85597 1
6.35149 -2.56078 1
6.26716 -2.70585 1
6.96568 -2.49673 1
7.38966 -2.61692 1
6.53299 -2.9829 1
7.29134 -3.32464 1
6.19125 -2.56348 1
6.4553 -3.21695 1
6.51221 -2.95676 1
6.2846 -3.05132 1
6.44342 -2.36582 1
7.25319 -3.1791 1
-4.23389 -4.01247 2
-4.44115 -4.7724 2
-3.152 -7.64371 2
-4.60689 -5.17812 2
-3.52225 -5.65851 2
-4.46773 -4.31933 2
-5.16101 -5.14835 2
-4.6625 -6.68859 2
-4.67434 -4.93988 2
-4.54051 -6.91158 2
-4.29897 -4.35503 2
-4.65625 -6.08671 2
-4.57752 -4.42068 2
-5.01582 -5.98163 2
-4.25558 -6.10923 2
-5.53808 -6.16271 2
-5.26016 -4.70259 2
-3.97634 -6.17944 2
-5.24988 -6.36019 2
-4.56382 -5.91064 2
-4.33442 -6.95979 2
2.76108 -7.70144 3
3.40997 -7.24725 3
4.90564 -9.39379 3
2.88351 -8.29924 3
2.97232 -9.29992 3
3.58827 -7.99622 3
1.68982 -6.79696 3
3.19298 -7.16005 3
3.16185 -8.59746 3
3.71499 -7.82042 3
3.7384 -9.11254 3
3.22514 -7.96381 3
3.7754 -8.82775 3
3.42263 -7.69458 3
-3.25131 10.4505 4
-4.05343 8.39821 4
-4.32351 6.70354 4
-3.00231 10.0173 4
-6.34827 6.41066 4
-1.56694 10.5506 4
-5.00159 8.98077 4
-5.27359 9.59971 4
-3.1084 8.83538 4
-5.5715 9.49135 4
-3.91482 7.65405 4
-3.71979 9.6507 4
4

1 回答 1

0

该错误可以很容易地重现:

test <- list(x=1, y=2)
test[[0]]

问题是这样的:

1:2-1
#[1] 0 1

也许你想要for(i in 1:(n-1)){

于 2013-09-13T23:25:21.050 回答