Home Ask Login Register

Developers Planet

Your answer is one click away!

Capsicum February 2016

R: Index matrix row-wise in vectors

I have a vector containing only character elements, say

v <- c("A","B","C")

and a matrix containing only logical elements, with width equal to the length of v and arbitrary length:

> M <- matrix(c(TRUE,FALSE,TRUE,FALSE,TRUE,TRUE),ncol=3)
> M
      [,1]  [,2] [,3]

Now I would like to index each row of M into v, collapse, and obtain a vector r each element of which contains the corresponding row of M in one character expression. In the example given, the elements of r would be

> r
"A C" "B C"

I can do this for each row separately (or within a loop), using

r[i] <- paste(v[as.logical(M[i,])], collapse="")

but hoped there would be a more efficient solution that deals with the full matrix at once.


akrun February 2016

We can use apply with MARGIN=1

apply(M, 1, function(x) paste(v[x], collapse=' '))
#[1] "A C" "B C"


 M <- matrix(c(TRUE,FALSE,TRUE,FALSE,TRUE,TRUE),ncol=3, byrow=TRUE)

Post Status

Asked in February 2016
Viewed 1,351 times
Voted 7
Answered 1 times


Leave an answer

Quote of the day: live life