R:如何将类别转换为列?
我有这样的数据:R:如何将类别转换为列?,r,reshape,R,Reshape,我有这样的数据: 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 我想将类别转换为包含频率(计数)的列,如下所示: Id Action timestamp 1
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
我想将类别转换为包含频率(计数)的列,如下所示:
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
#创建数据帧
df Id动作
#>1点击
#>2.1视图
#>3.1数据
#>4.2点击
#>5.2点击
#使用2::dcast
图书馆(E2)
dcast(df,Id~动作,fun.aggregate=长度)
#>Id单击“数据视图”
#> 1 1 1 1 1
#> 2 2 2 0 0
最快的方法是从“data.table”或“restrape2”中使用dcast
。有了这样的解决方案,答案就很多了。table(df$Id,df$Action)
基本包也会这样做如果你想保存击键,函数默认为lengthdcast(df,Id~Action)