[英]How to locate elements that meet a condition in one matrix to identify elements in a second matrix
I want to identify the positions of elements in one matrix that meet a condition to then apply those positions to another matrix and find the means of those. 我想确定一个矩阵中满足条件的元素的位置,然后将这些位置应用于另一矩阵并找到这些元素的均值。
my_vector_1<-c(1,2,1,4,1,1,7,8,)
my_matrix_1<-matrix(data=my_vector_1, nrow=3, ncol=3)
my_vector_2<-c(2,4,6,8,10,11,12,13,14)
my_matrix_2<-matrix(data=my_vector_2, nrow=3, ncol=3)
First locate the positions of my_matrix_1==1
in the first matrix to find... 首先在第一个矩阵中找到my_matrix_1==1
的位置以查找...
[1,1]
[2,2]
[3,1]
[3,2]
Then find the mean of the elements in the second matrix that are in the positions identified above... 然后找到第二个矩阵中位于上述位置的元素的均值...
7.25 #mean of 2, 10, 6, 11 in my_matrix_2
You could subset my_matrix_2
where my_matrix_1
has value 1 and take mean
of those values. 你可以子集my_matrix_2
其中my_matrix_1
的值为1,并采取mean
这些值。
mean(my_matrix_2[my_matrix_1 == 1])
#[1] 7.25
We can use arr.ind
to find the row/column position 我们可以使用arr.ind
查找行/列的位置
ind <- which(my_matrix_1 == 1, arr.ind = TRUE)
ind
# row col
#[1,] 1 1
#[2,] 3 1
#[3,] 2 2
#[4,] 3 2
mean(my_matrix_2[ind])
#7.25
Another way to do this would be 另一种方法是
mean(my_matrix_2 * NA^(my_matrix_1 != 1), na.rm = TRUE)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.