rp438
rp438

Reputation: 3

How to concatenate multiple column values based on a matrix in R

I have a matrix of binary values I want to use to return different subsets of values from a vector.

This seems like it would be simple, but I can't do anything to generate the desired result

G <- as.matrix(data.frame(a=c(0,0,1,0),b=c(1,1,0,0),c=c(1,0,0,1),d=c(0,1,0,0)))
c <- colnames(G)
> G
     a b c d
[1,] 0 1 1 0
[2,] 0 1 0 1
[3,] 1 0 0 0
[4,] 0 0 1 0

The result I want is:

[1] "b,c" "b,d" "a"   "c"

Please help!

Upvotes: 0

Views: 54

Answers (2)

Cole
Cole

Reputation: 11255

Here's another approach that converts 0 and 1 to FALSE and TRUE to subset the colnames:

apply(G, 1, function(x) paste(c[as.logical(x)], collapse = ','))

[1] "b,c" "b,d" "a"   "c"   

Upvotes: 0

d.b
d.b

Reputation: 32548

sapply(1:nrow(G), function(i) toString(names(G[i, G[i,] == 1])))
#OR
with(data.frame(which(G == 1, arr.ind = TRUE)),
     unname(sapply(split(colnames(G)[col], row), toString)))
#[1] "b, c" "b, d" "a"    "c"

If you have newer version of R, you could also do

sapply(asplit(G, 1), function(x) toString(names(x)[x == 1]))

Upvotes: 1

Related Questions