1

I have an 8 by 3 matrix like this:

  A B C
1 1 1 1
2 1 1 2
3 1 2 1
4 1 2 2
5 2 1 1
6 2 1 2
7 2 2 1
8 2 2 2

I want to create a column vector from this matrix like this:

cell
111
112
121
122
211
212
221
222

This means converting all the 3 columns into a single column. How can I do this? what are the codes?

Dihan
  • 311
  • 1
  • 7

2 Answers2

2

We can use paste

data.frame(cell = as.integer(do.call(paste0, df1)))

-output

#  cell
#1  111
#2  112
#3  121
#4  122
#5  211
#6  212
#7  221
#8  222

NOTE: In the reproducible example, we used data.frame as input. If it is a matrix, convert to data.frame with as.data.frame and apply the same code


Or use unite

library(tidyr)
library(dplyr)
unite(df1, cell, everything(), sep="") %>%
    type.convert(as.is = TRUE)

data

df1 <- structure(list(A = c(1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L), B = c(1L, 
1L, 2L, 2L, 1L, 1L, 2L, 2L), C = c(1L, 2L, 1L, 2L, 1L, 2L, 1L, 
2L)), class = "data.frame", row.names = c("1", "2", "3", "4", 
"5", "6", "7", "8"))
akrun
  • 874,273
  • 37
  • 540
  • 662
0

Use matrix multiplication as follows:

m %*% 10^(2:0)

giving:

  [,1]
1  111
2  112
3  121
4  122
5  211
6  212
7  221
8  222

Note

m in reproducible form:

Lines <- "
  A B C
1 1 1 1
2 1 1 2
3 1 2 1
4 1 2 2
5 2 1 1
6 2 1 2
7 2 2 1
8 2 2 2"
m <- as.matrix(read.table(text = Lines))
G. Grothendieck
  • 254,981
  • 17
  • 203
  • 341