0

I have the following data:

id       brand       quantity
1        a           2
1        b           1
2        b           5
3        c           10
2        d           11
3        a           1
4        b           2

The output should be

   a  b  c  d
1  2  1  0  0
2  0  5  10 11
3  1  0  10 0
4  0  2  0  0

How to get this type of sort in R language where the column names are brand types and row names are customer ids and the matrix data are quantity?

Veve
  • 6,643
  • 5
  • 39
  • 58
Maddy
  • 146
  • 1
  • 12

1 Answers1

1

This can be done with reshape() and a couple of post hoc fixups:

res <- reshape(df,dir='w',timevar='brand')[-1L];
names(res) <- sub('^quantity\\.','',names(res));
res[is.na(res)] <- 0L;
res;
##   a b  c  d
## 1 2 1  0  0
## 3 0 5  0 11
## 4 1 0 10  0
## 7 0 2  0  0

Data

df <- data.frame(id=c(1L,1L,2L,3L,2L,3L,4L),brand=c('a','b','b','c','d','a','b'),quantity=c(
2L,1L,5L,10L,11L,1L,2L),stringsAsFactors=F);
bgoldst
  • 34,190
  • 6
  • 38
  • 64
  • 1
    Is there a reason why you use `;` in R code? – talat Jun 20 '16 at 10:33
  • @docendodiscimus I've been grilled about this before; see http://stackoverflow.com/questions/29004672/using-user-defined-for-loop-function-to-construct-a-data-frame/29004774#comment46255949_29004774 and http://stackoverflow.com/questions/29534780/r-calculate-rank-sum-automatically/29534937#comment47223633_29534937. – bgoldst Jun 20 '16 at 10:35
  • 1
    I see what you mean, thanks – talat Jun 20 '16 at 10:36