Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R: How to convert categories to columns? [duplicate]

Tags:

r

reshape

I have data like this:

Id Action timestamp
1   click    #########
1    view    #########
1    data    #########
2    click   #########
2   click    #########

I want to convert the categories into columns containing frequency(counts) like this:

id click view data
1    1    1     1
2    2    0     0 

How can I do this? Thanks !

like image 904
UD1989 Avatar asked Mar 14 '23 17:03

UD1989


1 Answers

Here is how you can do it.

# create the data frame
df <- data.frame(Id=c(1,1,1,2,2), Action=c("click", "view", "data", "click", "click"))
df
#>   Id Action
#> 1  1  click
#> 2  1   view
#> 3  1   data
#> 4  2  click
#> 5  2  click

# Use reshape2::dcast
library(reshape2)
dcast(df, Id ~ Action, fun.aggregate = length)
#>   Id click data view
#> 1  1     1    1    1
#> 2  2     2    0    0
like image 103
Selva Avatar answered Mar 23 '23 16:03

Selva