ILoveThisName
ILoveThisName

Reputation: 13

Convert matrix to vector by a column to be one

I have a matrix like this:

     [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[1,] I1   I1   I1   I1   I2   I2   I2   I3   I3   I4
[2,] I2   I3   I4   I5   I3   I4   I5   I4   I5   I5

How can I make each column to be one vector, then make one vector for all?

[1]  I1,I2 I1,I3 I1,I4 I1,I5 I2,I3 I2,I4 I2,I5 I3,I4 I3,I5 I4,I5 

I have try this, but the result is not what i want...

sapply(b,function(i) paste(b[,i],collapse=","))

Upvotes: 0

Views: 458

Answers (2)

josliber
josliber

Reputation: 44340

It would be faster (assuming you have more columns than rows) and less typing to use paste0 to combine the two rows of your matrix, sticking a comma in between:

paste0(mat[1,], ",", mat[2,])
# [1] "I1,I2" "I1,I3" "I1,I4" "I1,I5" "I2,I3" "I2,I4" "I2,I5" "I3,I4" "I3,I5" "I4,I5"

Data:

mat <- combn(paste0("I", 1:5), 2)

Upvotes: 1

Greenparker
Greenparker

Reputation: 272

Fixed sapply use.

> b <- matrix(1:20, nrow = 2, ncol = 10)

> sapply(1:ncol(b), function(i) paste(b[,i],collapse=","))
 [1] "1,2"   "3,4"   "5,6"   "7,8"   "9,10"  "11,12" "13,14" "15,16"
 [9] "17,18" "19,20"

Upvotes: 0

Related Questions