2021年2月6日星期六

Transpose a Data Frame to Binary Matrix in R

I have a data frame with 2 columns, customerID and StockCodes describing stockcodes bought by the customer over a period of time. There could be multiple observation for the same customer as he might have bought the same items multiple times or different items over a period of time. The sammple data looks as follows.

CustomerID---StockCode

12346----------23166

12347---------16008

12347---------17021

12347---------20665

12347------- 20719

12347--------20719

12347--------20719

12347--------20719

12347--------20780

12347--------20782

12347--------20966

12347--------21035

I need to transpose the data frame in R such that all stockcodes would appear as columns without any repetition and each row will have distinct customerID. I have 2 questions 1) The cross-section cell value will have either numeric '1' if the customer has at least one matching stock code else 0. 2) The cross-section cell will have count of stockcodes each customer has, if there is a matching stock code, else 0.

https://stackoverflow.com/questions/66054912/transpose-a-data-frame-to-binary-matrix-in-r February 05, 2021 at 06:39AM

没有评论:

发表评论