鉴于m :
m <- structure(c(5, 1, 3, 2, 1, 4, 5, 2, 5, 1, 1, 5, 1, 4, 0, 4, 5, 5, 3, 2, 0, 0, 3, 0, 3, 2, 3, 0, 0, 0, 0, 0, 0, 0, 0), .Dim = c(7L, 5L)) # [,1] [,2] [,3] [,4] [,5] # [1,] 5 2 0 0 0 # [2,] 1 5 4 3 0 # [3,] 3 1 5 0 0 # [4,] 2 1 5 3 0 # [5,] 1 5 3 2 0 # [6,] 4 1 2 3 0 # [7,] 5 4 0 0 0考虑元素1 ,它出现在5行(2, 3, 4, ,5, 6) ,并且相应的列方向索引是(1, 2, 2, 1, 2) 1,2,2,1,2 (1, 2, 2, 1, 2) 。 我想有以下几点:
1 2 1 1 3 2 1 4 2 1 5 1 1 6 2作为另一个例子,考虑元素2 ,它出现在4行(1, 4, 5, 6) ,并且相应的列方向索引是(2, 1, 4, 3) 2,1,4,3 (2, 1, 4, 3)并且我们具有:
1 2 1 1 3 2 1 4 2 1 5 1 1 6 2 2 1 2 2 4 1 2 5 4 2 6 3我想要的是所有1-5的n*3矩阵。 优选在基础R中
Given m:
m <- structure(c(5, 1, 3, 2, 1, 4, 5, 2, 5, 1, 1, 5, 1, 4, 0, 4, 5, 5, 3, 2, 0, 0, 3, 0, 3, 2, 3, 0, 0, 0, 0, 0, 0, 0, 0), .Dim = c(7L, 5L)) # [,1] [,2] [,3] [,4] [,5] # [1,] 5 2 0 0 0 # [2,] 1 5 4 3 0 # [3,] 3 1 5 0 0 # [4,] 2 1 5 3 0 # [5,] 1 5 3 2 0 # [6,] 4 1 2 3 0 # [7,] 5 4 0 0 0Consider the element 1, it appears in 5 rows (2, 3, 4, ,5, 6) and the respective column-wise indices are (1, 2, 2, 1, 2). I would like to have the following:
1 2 1 1 3 2 1 4 2 1 5 1 1 6 2As another example, consider the element 2, it appears in 4 rows (1, 4, 5, 6) and the respective column-wise indices are (2, 1, 4, 3) and we have:
1 2 1 1 3 2 1 4 2 1 5 1 1 6 2 2 1 2 2 4 1 2 5 4 2 6 3What I want is a n*3 matrix for all 1-5. Preferably in base R
最满意答案
我们可以使用arr.ind=TRUE
cbind(val= 1, which(m==1, arr.ind=TRUE)) # val row col #[1,] 1 2 1 #[2,] 1 5 1 #[3,] 1 3 2 #[4,] 1 4 2 #[5,] 1 6 2对于多个案例,如@RHertel所述
for(i in 1:5) print(cbind(i,which(m==i, arr.ind=TRUE)))或与lapply
do.call(rbind, lapply(1:2, function(i) { m1 <-cbind(val=i,which(m==i, arr.ind=TRUE)) m1[order(m1[,2]),]})) # val row col #[1,] 1 2 1 #[2,] 1 3 2 #[3,] 1 4 2 #[4,] 1 5 1 #[5,] 1 6 2 #[6,] 2 1 2 #[7,] 2 4 1 #[8,] 2 5 4 #[9,] 2 6 3正如OP提到有关base R解决方案,上述内容将有所帮助。 但是,如果有人想要一个紧凑的解决方案,
library(reshape2) melt(m)然后将感兴趣的值分组。
We can use which with arr.ind=TRUE
cbind(val= 1, which(m==1, arr.ind=TRUE)) # val row col #[1,] 1 2 1 #[2,] 1 5 1 #[3,] 1 3 2 #[4,] 1 4 2 #[5,] 1 6 2For multiple cases, as @RHertel mentioned
for(i in 1:5) print(cbind(i,which(m==i, arr.ind=TRUE)))Or with lapply
do.call(rbind, lapply(1:2, function(i) { m1 <-cbind(val=i,which(m==i, arr.ind=TRUE)) m1[order(m1[,2]),]})) # val row col #[1,] 1 2 1 #[2,] 1 3 2 #[3,] 1 4 2 #[4,] 1 5 1 #[5,] 1 6 2 #[6,] 2 1 2 #[7,] 2 4 1 #[8,] 2 5 4 #[9,] 2 6 3As the OP mentioned about base R solutions, the above would help. But, in case, if somebody wants a compact solution,
library(reshape2) melt(m)and then subset the values of interest.
更多推荐
发布评论