Capsicum - 2 months ago 18

R Question

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`

`> 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`

`v`

`r`

`M`

`r`

`> 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.

Answer

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)
```