1

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

Matt
  • 7,255
  • 2
  • 12
  • 34

2 Answers2

0
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
Onyambu
  • 67,392
  • 3
  • 24
  • 53
0

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

Jan
  • 4,974
  • 3
  • 26
  • 43
  • 1
    Why would you use $ after using `with`? – Onyambu May 18 '22 at 08:23
  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community May 19 '22 at 06:53
  • The df that I used has more than these two columns that's why I use $ so I can define which column to use. – Ahmed Hassan May 19 '22 at 09:03