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
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)
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>)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With