[R] how to use a matrix as an index to another matrix?

Eric Berger er|cjberger @end|ng |rom gm@||@com
Fri Oct 11 12:30:30 CEST 2019


Here is one way
A <- sapply(1:ncol(A), function(i) {A[,i][B[,i]]})


On Fri, Oct 11, 2019 at 12:44 PM Jinsong Zhao <jszhao using yeah.net> wrote:

> Hi there,
>
> I have two matrices, A and B. The columns of B is the index of the
> corresponding columns of A. I hope to rearrange of A by B. A minimal
> example is following:
>
>  > set.seed(123)
>  > A <- matrix(sample(1:10), nrow = 5)
>  > B <- matrix(c(sample(1:5), sample(1:5)), nrow =5, byrow = FALSE)
>  > A
>       [,1] [,2]
> [1,]    3    9
> [2,]   10    1
> [3,]    2    7
> [4,]    8    5
> [5,]    6    4
>  > B
>       [,1] [,2]
> [1,]    2    1
> [2,]    3    4
> [3,]    1    5
> [4,]    4    3
> [5,]    5    2
>  > A[,1] <- A[,1][B[,1]]
>  > A[,2] <- A[,2][B[,2]]
>  > A
>       [,1] [,2]
> [1,]   10    9
> [2,]    2    5
> [3,]    3    4
> [4,]    8    7
> [5,]    6    1
>
> My question is whether there is any elegant or generalized way to replace:
>
>  > A[,1] <- A[,1][B[,1]]
>  > A[,2] <- A[,2][B[,2]]
>
> Thanks in advance.
>
> PS., I know how to do the above thing by loop.
>
> Best,
> Jinsong
>
> ______________________________________________
> R-help using r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide
> http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>

	[[alternative HTML version deleted]]



More information about the R-help mailing list