【问题标题】:Reshaping data with count [duplicate]用计数重塑数据[重复]
【发布时间】:2014-09-20 08:28:45
【问题描述】:

我有一个数据集,我想使用 R 中的包 reshape2 对其进行整形,但出现此错误:

Aggregation function missing: defaulting to length

这是我的数据的 head():

cat_one customer valor
cama        A     1
cama        B     1
cama        C     1
mesa        D     1
mesa        A     1
mesa        A     1

我想像这样重塑它,在两个变量之间进行计数:

customer     cama    mesa
A             1       0
B             2      ...
C
D            ...     ...

这是我的代码:

dcast(dados_teste, cat_one ~ customer, value.var = 'valor')

我正在关注另一个question,但同样的解决方案对我不起作用。

【问题讨论】:

    标签: r reshape2


    【解决方案1】:

    您混淆了公式的 LHS 和 RHS。

    试试:

    library(reshape2)
    dcast(dados_teste, customer ~ cat_one, value.var = "valor")
    # Aggregation function missing: defaulting to length
    #   customer cama mesa
    # 1        A    1    2
    # 2        B    1    0
    # 3        C    1    0
    # 4        D    0    1
    

    您所指的“错误”实际上只是一个warning,它告诉您它只是在计算值的数量——而不是应用任何其他函数。所以,在这种情况下,这是完全可以接受的。

    如果你想摆脱它,指定fun.aggregate = length

    dcast(dados_teste, customer ~ cat_one, 
          value.var = "valor", fun.aggregate = length)
    

    如果它只计算您所关注的两列,您还可以查看table

    as.data.frame.matrix(table(dados_teste[c(2, 1)]))
    #   cama mesa
    # A    1    2
    # B    1    0
    # C    1    0
    # D    0    1
    

    【讨论】:

      猜你喜欢
      • 2012-10-01
      • 2017-04-05
      • 2019-05-29
      • 1970-01-01
      • 2014-01-31
      • 2012-04-08
      • 1970-01-01
      相关资源
      最近更新 更多