Extract and store a specific position from multiple matrices in an array in R

余生长醉 提交于 2019-12-13 00:55:38

问题


Sorry, newbie... I've got an array object called "y" of 500 matrices of 6x6, like this:

, , 1
       [,1]   [,2]   [,3]   [,4]   [,5]   [,6]
[1,] 0.0000 0.3627 0.4132 0.4231 0.3795 0.5444
[2,] 0.3627 0.0000 0.2084 0.3523 0.2310 0.5377
[3,] 0.4132 0.2084 0.0000 0.1984 0.2920 0.4774
[4,] 0.4231 0.3523 0.1984 0.0000 0.2787 0.4363
[5,] 0.3795 0.2310 0.2920 0.2787 0.0000 0.5129
[6,] 0.5444 0.5377 0.4774 0.4363 0.5129 0.0000

[...]

, , 500
       [,1]   [,2]   [,3]   [,4]   [,5]   [,6]
[1,] 0.0000 0.3755 0.3568 0.3835 0.3582 0.5065
[2,] 0.3755 0.0000 0.0840 0.2253 0.2237 0.4066
[3,] 0.3568 0.0840 0.0000 0.1673 0.2434 0.4073
[4,] 0.3835 0.2253 0.1673 0.0000 0.2338 0.3403
[5,] 0.3582 0.2237 0.2434 0.2338 0.0000 0.4263
[6,] 0.5065 0.4066 0.4073 0.3403 0.4263 0.0000

I want to extract a specific position through all the 500 matrices in the array and store this 500 values in a vector named "unouno" for further analyses

I'm trying to do this:

for (i in 1:dim(y)[[3]]){
unouno<-y[2,1,i, drop=F]
}

but it only extracts the value for the last (500th) matrix.

(Once solved this I want to extract and store separately the 500 values of each of the 6 x 6 positions in the matrices)


回答1:


If you would like to fix your loop, this could be one way to do it:

unouno <- NULL
for (i in 1:dim(y)[3]){
  unouno[i]<-y[2,1,i]
}

It seems that you were mising indexing on the vector unouno as well




回答2:


We can do this by leaving the 3rd dimension blank

y[2,1,]

data

y <- array(1:60, dim=c(10,2,3))


来源:https://stackoverflow.com/questions/33033950/extract-and-store-a-specific-position-from-multiple-matrices-in-an-array-in-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!