bumblebee
bumblebee

Reputation: 1116

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,byrow=TRUE)
> M
      [,1]  [,2] [,3]
[1,]  TRUE FALSE TRUE
[2,] FALSE  TRUE TRUE

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.

Upvotes: 1

Views: 210

Answers (1)

akrun
akrun

Reputation: 887981

We can use apply with MARGIN=1

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

data

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

Upvotes: 1

Related Questions