mercredi 23 mai 2018

dcast with if statement in r

I am trying to reshape dataframe

cust_id<-sample(1:20,size = 100,replace = T)
prod_id<-sample(1:10,size=100,replace = T)
prod_id<-paste0("prodid",prod_id)
atm<-sample(1:10,size=100,replace = T)*100
atm[(sample(1:100,size=30,replace =F ))]<-0
sales<-data.frame(cust_id,prod_id,atm)  
sales

here is sales dataframe if i want to change data.frame like this

(if atm > 0 by cust_id, prod_id then value=1 and atm < 0 by cust_id, prod_id then value=0)

           cust_id prod_id1  prod_id2 prod_id3 prod_id4 ....
              1      1          0        1       0
              11     0          0        0       1
              23     0          0        1       0
              5      1          1        1       1

i tried to make it with dcast function. but i can't use if statement in dcast.

please help...

Aucun commentaire:

Enregistrer un commentaire