Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/67.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Arrays 将数组的每个对应元素转换为r中的向量_Arrays_R - Fatal编程技术网

Arrays 将数组的每个对应元素转换为r中的向量

Arrays 将数组的每个对应元素转换为r中的向量,arrays,r,Arrays,R,我有大量的数组,我想把所有数组中特定位置的元素都转换成一个向量。也就是说,如果我有2个arrya,如下所示: , , 39 [,1] [,2] [,3] [,4] [,5] [1,] 0.00000000 0.00000000 0.0000000 0.000000 0 [2,] 0.06703875 0.00000000 0.0000000 0.000000 0 [3,] 0.60078853 0.48239

我有大量的数组,我想把所有数组中特定位置的元素都转换成一个向量。也就是说,如果我有2个arrya,如下所示:

, , 39

            [,1]        [,2]       [,3]     [,4] [,5]
[1,]  0.00000000  0.00000000  0.0000000 0.000000    0
[2,]  0.06703875  0.00000000  0.0000000 0.000000    0
[3,]  0.60078853  0.48239226  0.0000000 0.000000    0
[4,] -0.41071928 -0.03397696 -1.3588026 0.000000    0
[5,] -0.27326482  0.84172740 -0.3139296 1.515104    0

, , 40

            [,1]       [,2]      [,3]    [,4] [,5]
[1,] 0.000000000  0.0000000 0.0000000 0.00000    0
[2,] 0.003862625  0.0000000 0.0000000 0.00000    0
[3,] 0.187788593 -0.1087561 0.0000000 0.00000    0
[4,] 0.186767234  0.2369021 0.2967447 0.00000    0
[5,] 1.008507457  0.7118111 0.1412379 1.02506    0
然后我想有10个向量,如下所示(仅下三角形处的值):

因此,所有位于同一位置的元素将被存储到一个向量中。
我有300个这样的数组,希望在R中自动执行。有什么想法和帮助吗?

您可以使用
应用于下三角的子集,但它会将其结果简化为矩阵(实际上可能是更好的数据结构)。要将该矩阵拆分为向量,您可以使用一系列行数的
split
,这些行数将根据需要循环,因为如果您只提供一个索引,矩阵将按列进行子集划分(填充时)。总而言之:

set.seed(47)

a使用
aperm
和逻辑子集的替代方法是

# Use array provided in alistaire's answer, modified to set the upper triangle to 0
set.seed(47)
a <- array(rnorm(5 * 5 * 2), c(5, 5, 2))
for(i in 1:2) a[,,i][upper.tri(a[,,i], diag = TRUE)] <- 0
现在,提取非零元素并将其放入矩阵中:

myMat <- matrix(tmp[tmp != 0], 2)

请参阅comperes软件包和函数mat_to_long()

库(主持人)

long.dat请使用
dput
发布可复制的示例。
tmp <- aperm(a, c(3, 2, 1))
myMat <- matrix(tmp[tmp != 0], 2)
split(myMat, col(myMat))
$`1`
[1]  0.7111425 -1.6081599

$`2`
[1]  0.1854053 -2.3223723

$`3`
[1]  0.01513086 -1.20044063

...
library(comperes)
long.dat <- mat_to_long(matrix, "row", "col", "val")