tushaR
tushaR

Reputation: 3116

acast from long to wide format

I have a data.frame "uiq" in the following format:

          CNS_CD       PROD_CD          QTY
1         M00000001    CFGO301WABU       1
2         M00000002    DFGK122EARE       1
3         M00000002    CWGO154COGY       1
4         M00000004    CWGC003COTA       1
5         M00000005    CWGC002COTA       1
6         M00000005    CFDC002COTA       1
7         M00000006    CFDT202AISL       1
8         M00000007    CFDO309FIPE       1
9         M00000007    CWGO314WABU       1
10        M00000007    CWGO326EAVI       1
11        M00000008    CFDO203COOW       1
12        M00000009    CWGK323EABL       1
13        M00000010    CFDO326EAVI       1
14        M00000010    CWGT337EANY       1
15        M00000011    CFDO203FIVI       1

I need to covert this data to a matrix such that I have a count of quantity for each item in PROD_CD against every CNS_CD.
If some PROD_CD is not listed against a CNS_CD still it should be there in the matrix with value 0. Trying to convert it to a user-item matrix format with count.

class(CNS_CD), class(PROD_CD) is "character". I tried this:

acast(data = uiq,formula = CPH_CNS_CD~PROD_CD,fun.aggregate = count,value.var = uiq$QTY)

and got this error:

Error: value.var (1111111111111111111111111111111111111111111111111111
In addition: Warning message:
In if (!(value.var %in% names(data))) { :
the condition has length > 1 and only the first element will be used

It somehow works when the fun.aggregate and value.var parameters are not supplied with the same function. What is the issue here or is there some alternate way too to achieve the required format?

     CNS_CD       CFGO301WABU    DFGK122EARE    CWGO154COGY    CWGC003COTA .....
     M00000001         1            0               0             0
     M00000002         0            1               1             0
     M00000004         0            0               0             1

Upvotes: 1

Views: 117

Answers (1)

akrun
akrun

Reputation: 887311

We can use length

acast(data = uiq,formula = CNS_CD~PROD_CD,fun.aggregate = length,value.var =  "QTY")

Upvotes: 1

Related Questions