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?

1
  • Numeric would be better! Commented May 19, 2021 at 2:17

2 Answers 2

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"))
Sign up to request clarification or add additional context in comments.

Comments

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

2 Comments

why do you use 10^(2:0)?
It gives c(100,10,1) without writing it out.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.