【问题标题】:Aggregate on one filed and horizontal table on other [duplicate]在一个字段上聚合,在另一个字段上聚合水平表[重复]
【发布时间】:2018-02-23 07:47:18
【问题描述】:

我有一个包含各种字段的数据集,我想将它聚合到 1 列并在其他列上水平制表

Region  Device
a   ios
a   chrome
a   safari
a   ios
a   chrome
b   chrome
b   chrome
b   safari
c   ios
c   chrome
c   ios

我希望输出是这样的

Region  ios Chrome  safari
a   2   2   1
b   0   2   1
c   2   1   0

我的最终目的是制作表格和图形表示

【问题讨论】:

  • 区域设备 a ios a chrome a safari a ios a chrome b chrome b chrome b safari c ios c chrome c ios
  • 试试table(df$Region, df$Device)(如果您的数据存储在名为 df 的数据帧中)

标签: r data-mining


【解决方案1】:

使用基础 R:

> dat
   Region Device
1       a    ios
2       a chrome
3       a safari
4       a    ios
5       a chrome
6       b chrome
7       b chrome
8       b safari
9       c    ios
10      c chrome
11      c    ios
> xtabs(s~Region+Device,cbind(dat,s=1))
      Device
Region chrome ios safari
     a      2   2      1
     b      2   0      1
     c      1   2      0

使用 reshape2 包:

> library(reshape2)
> dcast(dat,Region~Device,length,value.var="Device")
  Region chrome ios safari
1      a      2   2      1
2      b      2   0      1
3      c      1   2      0
> 

【讨论】:

    猜你喜欢
    • 2018-06-16
    • 2021-06-23
    • 2023-02-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-22
    • 1970-01-01
    相关资源
    最近更新 更多