list - R: Index matrix row-wise in vectors -
i have vector containing character elements, say
v <- c("a","b","c")
and matrix containing logical elements, width equal length of v
, 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 index each row of m
v
, collapse, , obtain vector r
each element of contains corresponding row of m
in 1 character expression. in example given, elements of r
> r "a c" "b c"
i can each row separately (or within loop), using
r[i] <- paste(v[as.logical(m[i,])], collapse="")
but hoped there more efficient solution deals full matrix @ once.
we can use apply
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)
Comments
Post a Comment