0

I have a raw dataset like this:

ID  Click  
1   A  
1   B  
1   E  
2   A  
2   Q  
3   B  
3   D  
3   F  

And what I am planning to do is to transpose it into a sparse matrix like this:

ID  A   B   D   E   Q   F    
1   1   1   0   1   0   0  
2   1   0   0   0   1   0  
3   0   1   1   0   0   1  

The column number of a sparse matrix is numbers of unique 'click' value in raw data. The row number of sparse matrix is the numbers of unique 'ID' numbers in raw data. If the "click" appears in a specific ID in raw dataset, then the value will be 1, otherwise the value is 0.

I tried reshape() function in R but it's not work. Can anyone help with it? Thanks!

Iris.W
  • 23
  • 6

1 Answers1

-1

You can do something like this:

library(tidyverse)

dat <- tribble(~"ID",  ~"Click",
          1,   "A",  
          1,   "B",  
          1,   "E",  
          2,   "A",  
          2,   "Q",  
          3,   "B",  
          3,   "D",  
          3,   "F")

table(dat)
#> ID  A B D E F Q
#>   1 1 1 0 1 0 0
#>   2 1 0 0 0 0 1
#>   3 0 1 1 0 1 0

Created on 2019-02-25 by the reprex package (v0.2.1)

EDIT: To clarify my post you don't need library(tidyverse) or to build your data with tribble() the function you are looking for is table()

dylanjm
  • 2,011
  • 9
  • 21
  • Not sure why I'm getting downvotes. My answer is the correct method of doing things and OP didn't provide their data in an easy to consume way so I used `tribble()` – dylanjm Feb 25 '19 at 16:23
  • thanks so much! Really not sure who downvoted this answer, it works! – Iris.W Feb 26 '19 at 20:43