Home > OS >  Make a matrix out of a df in R
Make a matrix out of a df in R

Time:05-18

So I have a table that looks something like this

name <- c("AGTC","ATTC","ATGC", "ATCC")
Var1 <- c("TRA11","TRA8","TRA9", "TRA9")
Var2 <- c("TRB1", "TRB15", "TRB7", "TRB7")
df <-data.frame(name, Var1, Var2)

df
  name  Var1  Var2
1 AGTC TRA11  TRB1
2 ATTC  TRA8 TRB15
3 ATGC  TRA9  TRB7
4 ATCC  TRA9  TRB7

I want a matrix like this so I can plot a circos plot

       TRA11  TRA8  TRA9 
TRB1     1      0     0
TRB15    0      1     0
TRB7     0      0     2

I managed to fix start with the matrix but I have no idea how to fill the values in,

A <- sort(unique(unlist(strsplit(paste(df$Var1, collapse=","), ","))))
B <- sort(unique(unlist(strsplit(paste(eee$Var2, collapse=","), ","))))
mat <- matrix(nrow = length(A), ncol = length(B))
colnames(mat) <- B
rownames(mat) <- A

mat
       TRA11  TRA8  TRA9 
TRB1     0      0     0
TRB15    0      0     0
TRB7     0      0     0

I would appreciate any help.

Thanks a lot

CodePudding user response:

table(df[-1])

       Var2
Var1    TRB1 TRB15 TRB7
  TRA11    1     0    0
  TRA8     0     1    0
  TRA9     0     0    2

If you want it as a dataframe:

as.data.frame.matrix(table(df[-1]))

      TRB1 TRB15 TRB7
TRA11    1     0    0
TRA8     0     1    0
TRA9     0     0    2

CodePudding user response:

So I managed to do it this way,

tb <- with(df, table(df$Var1, df$Var2))
a <- as.matrix(tb)
and it worked like a charm

Thanks guys

  • Related