Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reshaping data table to make column names into row names

I have a data.table in R

> dt
  SAMPLE   junction count
1: R1        a       1
2: R2        a       1
3: R3        b       1
4: R3        a       1
5: R1        c       2

Now I want to "reshape" the data table to form a data frame m (basically junction by sample matrix with index value to be corresponding count value). Also, observe that for (SAMPLE,junction) pairs that don't exist in dt, I am assuming the corresponding count value to be zero. Could someone help me how to achieve this?

> m
      R1   R2   R3
  a    1    1    1
  b    0    0    1
  c    2    0    0
like image 297
hi15 Avatar asked Apr 13 '15 07:04

hi15


2 Answers

The dcast from data.table changes the dataset from 'long' to 'wide' format.

library(data.table)#v1.9.5+
dcast(dt, junction~SAMPLE, value.var='count', fill=0)
#   junction R1 R2 R3
#1:        a  1  1  1
#2:        b  0  0  1
#3:        c  2  0  0

If you need a matrix output

library(reshape2)
acast(dt, junction~SAMPLE, value.var='count', fill=0)
#   R1 R2 R3
#a  1  1  1
#b  0  0  1
#c  2  0  0

Or xtabs from base R

 xtabs(count~junction+SAMPLE, dt)
like image 154
akrun Avatar answered Oct 19 '22 21:10

akrun


An alternative approach using spread from tidyr:

library(tidyr)

spread(dt, SAMPLE, count, fill=0)
#   junction R1 R2 R3
#1:        a  1  1  1
#2:        b  0  0  1
#3:        c  2  0  0

Or old school solution with reshape from stats:

reshape(dt, timevar='SAMPLE', idvar=c('junction'), direction='wide')
#   junction count.R1 count.R2 count.R3
#1:        a        1        1        1
#2:        b       NA       NA        1
#3:        c        2       NA       NA

Data:

dt = structure(list(SAMPLE = c("R1", "R2", "R3", "R3", "R1"), junction = c("a", 
"a", "b", "a", "c"), count = c(1, 1, 1, 1, 2)), .Names = c("SAMPLE", 
"junction", "count"), row.names = c(NA, -5L), class = c("data.table", 
"data.frame"), .internal.selfref = <pointer: 0x05e924a0>)
like image 27
Colonel Beauvel Avatar answered Oct 19 '22 19:10

Colonel Beauvel