1

I have a data frame in R that I need to manipulate (pivot). At the simplest level the first few rows would look like the following:

Batch  Unit  Success InputGrouping
1       1     1       A
2       5     1       B
3       4     0       C
1       1     1       D
2       5     1       A

I would like to pivot this data so that the column names would be InputGrouping and the values would be 1 if it exists and 0 if not. Using above:

Batch  Unit  Success  A   B  C  D
1       1     1       1   0  0  1
2       5     1       1   1  0  0
3       4     0       0   0  1  0

I've looked at reshape/cast but can't figure out if this transformation is possible with the package. Any advice would be very much appreciated.

chemnteach
  • 375
  • 8
  • 23

2 Answers2

5

This is indeed possible using reshape2 with the function dcast().

Recreate your data:

dat <- read.table(header=TRUE, text="
Batch  Unit  Success InputGrouping
1       1     1       A
2       5     1       B
3       4     0       C
1       1     1       D
2       5     1       A")

Now recast the data:

library("reshape2")

dcast(Batch + Unit + Success ~ InputGrouping, data=dat, fun.aggregate = length)

The results:

Using InputGrouping as value column: use value.var to override.
  Batch Unit Success A B C D
1     1    1       1 1 0 0 1
2     2    5       1 1 1 0 0
3     3    4       0 0 0 1 0
Andrie
  • 176,377
  • 47
  • 447
  • 496
4

Here's a possible solution using the data.table package

library(data.table)
setDT(df)[, as.list(table(InputGrouping)), by = .(Batch, Unit, Success)]
#    Batch Unit Success A B C D
# 1:     1    1       1 1 0 0 1
# 2:     2    5       1 1 1 0 0
# 3:     3    4       0 0 0 1 0
David Arenburg
  • 91,361
  • 17
  • 137
  • 196