Francis Smart
Francis Smart

Reputation: 4055

R: Return a vector for each row of a matrix which lists what colum the value x is in

Okay, sorry I know this sounds unnecessarily confusing. I am basically looking to return a vector of elements equal to the number of rows with each element specifying where in the matrix the specified outcome occurred.

library(gtools)
(A <- permutations(3, 3))
     [,1] [,2] [,3]
[1,]    1    2    3
[2,]    1    3    2
[3,]    2    1    3
[4,]    2    3    1
[5,]    3    1    2
[6,]    3    2    1

Using the unknown function foo would return:

foo(A, match=1)
[1] 1 1 2 3 2 3
foo(A, match=2)
[1] 2 3 1 1 3 2

Thank you for any help you can provide!

Upvotes: 1

Views: 68

Answers (2)

thelatemail
thelatemail

Reputation: 93803

Use max.col and some indexing of the matrix:

> max.col(A==1)
[1] 1 1 2 3 2 3
> max.col(A==2)
[1] 2 3 1 1 3 2

Upvotes: 3

akrun
akrun

Reputation: 886938

Try

foo <- function(mat, match=1){
  indx <- which(mat==match, arr.ind=TRUE)
  indx[order(indx[,1]),2]
}

foo(A, 1)
#[1] 1 1 2 3 2 3
foo(A,2)
#[1] 2 3 1 1 3 2

Upvotes: 2

Related Questions