R - 数据表被视为因素,但事实并非如此

时间:2016-03-06 22:46:37

标签: r dataframe data.table aggregate

这次我真的很困惑,不知道该怎么办。 我有一个像这样的数据框

           ID     VALUE1     VALUE2    GROUP    MODEL
    # 1: id_1   0.5697779   17.6100597  Group_A  Model B
    # 2: id_10 246.7413330 6814.7109375  Group_A  Model_B
    # 3: id_100   0.0000000   26.5990372  Group_C  Model_F
    # 4: id_1000   0.0000000    0.0000000  Group_B  Model_D
    # 5: id_101 105.3097610  486.4001160  Group_C  Model_C
    # 6: id_102   0.0000000  108.9007416  Group_C  Model_C
    # 7: id_103   0.1306531    1.0070915  Group_C  Model_F
    # 8: id_104   0.0000000    0.5426522  Group_C  Model_F
    # 9: id_105   0.1352515    1.1137601  Group_C  Model_C
    # 10: id_106   0.0000000    0.2867465  Group_C  Model_C

我需要计算VALUE1VALUE2的汇总值。所以我做了

agg <- aggregate(cbind(dat[,"VALUE1"],dat[,"VALUE2"]), by = list(dat[,"GROUP"], dat[,"MODEL"]),FUN=sum)

但我得到

Summary.factor(structure(1L, .Label = "VALUE1", class = "factor"),  : 
‘sum’ not meaningful for factors

但如果我输入

apply(dat,2,is.factor)

给了我

ID       VALUE1    VALUE2    GROUP    MODEL
FALSE    FALSE     FALSE     FALSE    FALSE

为什么?我哪里错了?

编辑:dput(dat)我得到了

structure(list(ID = c("id_1", "id_10", "id_100", 
"id_1000", "id_101", "id_102", "id_103", "id_104", 
"id_105", "id_106"), VALUE1 = c(0.56977790594101, 246.741333007812, 
0, 0, 105.309761047363, 0, 0.13065305352211, 0, 0.135251507163048, 
0), VALUE2 = c(17.6100597381592, 6814.7109375, 26.5990371704102, 
0, 486.400115966797, 108.900741577148, 1.0070915222168, 0.542652249336243, 
1.11376011371613, 0.28674653172493), GROUP = c("Group_A", 
"Group_A", "Group_C", "Group_B", "Group_C", "Group_C", 
"Group_C", "Group_C", "Group_C", "Group_C"), 
MODEL = c("Model_B", "Model_B", "Model_F", "Model_D", 
"Model_C", "Model_C", "Model_F", "Model_F", "Model_C", "Model_C"
)), .Names = c("ID", "VALUE1", "VALUE2", "GROUP", "MODEL"), sorted = "ID", class = c("data.table", 
"data.frame"), row.names = c(NA, -10L), .internal.selfref = <pointer: 0x97b5290>)
  ID          VALUE1     VALUE2 GROUP MODEL
1:     id_1   0.5697779   17.6100597       Group_A       Model_B
2:    id_10 246.7413330 6814.7109375       Group_A       Model_B
3:   id_100   0.0000000   26.5990372       Group_C       Model_F
4:   id_1000   0.0000000    0.0000000       Group_B       Model_D
5:   id_101 105.3097610  486.4001160       Group_C       Model_C
6:   id_102   0.0000000  108.9007416       Group_C       Model_C
7:   id_103   0.1306531    1.0070915       Group_C       Model_F
8:   id_104   0.0000000    0.5426522       Group_C       Model_F
9:   id_105   0.1352515    1.1137601       Group_C       Model_C
10:   id_106   0.0000000    0.2867465       Group_C       Model_C

0 个答案:

没有答案