将数组的每个对应元素转换为r中的向量 [英] Convert each corresponding elements of arrays to vector in r
问题描述
我有大量的数组,并且想在向量中将所有这些元素隐藏在所有这些数组的特定位置.也就是说,如果我有2个arryas,如下所示:
I have a large number of arrays and would like to covert all element at specific position in all these arrays in a vector. That is, if I have 2 arryas as follows:
, , 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个向量,如下所示(仅下三角的值):
Then I would like to have 10 vectors as follows (only the values at lower triangular):
v1( 0.06703875 , 0.003862625 )
v2(0.60078853 , 0.187788593 )
. . .
. . .
v10(1.515104 , 1.02506)
因此位于相同位置的所有元素都将存储到向量中.我有300百万个这样的数组,想在R中自动完成.有什么想法和帮助吗?
so all the element which are at the same position will be stored into a vector. I have 300 hundred such these arrays and would like to do it automatically in R. Any idea and help please?
推荐答案
您可以使用 apply
将其子集化到较低的三角形,但它将其结果简化为矩阵(实际上可能是一个矩阵更好的数据结构).要将矩阵拆分为向量,您可以对行数序列使用 split
,该行将根据需要进行回收,因为如果仅提供一个索引,矩阵将按列逐列(填充时).在一起:
You can use apply
to subset to the lower triangle, but it will simplify its result to a matrix (which may actually be a better data structure). To split that matrix into vectors, you can use split
with a sequence of the number of rows, which will recycle as you want because matrices subset column-wise (as they fill) if you only supply one index. All together:
set.seed(47)
a <- array(rnorm(5 * 5 * 2), c(5, 5, 2))
lower_tris <- apply(a, 3, function(x){x[lower.tri(x)]})
list_of_pairs <- split(lower_tris, seq(nrow(lower_tris)))
# or with @lmo's cleaner approach,
# list_of_pairs <- split(lower_tris, row(lower_tris))
str(list_of_pairs)
#> List of 10
#> $ 1 : num [1:2] 0.711 -1.608
#> $ 2 : num [1:2] 0.185 -2.322
#> $ 3 : num [1:2] -0.282 -1.967
#> $ 4 : num [1:2] 0.1088 0.0275
#> $ 5 : num [1:2] 0.0151 -1.2004
#> $ 6 : num [1:2] -0.252 0.885
#> $ 7 : num [1:2] -1.466 0.887
#> $ 8 : num [1:2] -1.828 0.507
#> $ 9 : num [1:2] 0.0915 0.5643
#> $ 10: num [1:2] -0.0406 -0.4877
split
通过拆分因子自动命名每个元素;如果愿意,可以将通话包裹在 unname
中.
split
automatically names each element by the splitting factor; wrap the call in unname
if you like.
这篇关于将数组的每个对应元素转换为r中的向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!