R:如何将类别转换为列?
R: How to convert categories to columns?
我有这样的数据:
Id Action timestamp
1 click #########
1 view #########
1 data #########
2 click #########
2 click #########
我想将类别转换为包含频率(计数)的列,如下所示:
id click view data
1 1 1 1
2 2 0 0
我该怎么做?谢谢!
这里是你如何做到的。
# 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
我有这样的数据:
Id Action timestamp
1 click #########
1 view #########
1 data #########
2 click #########
2 click #########
我想将类别转换为包含频率(计数)的列,如下所示:
id click view data
1 1 1 1
2 2 0 0
我该怎么做?谢谢!
这里是你如何做到的。
# 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