R中的聚合函数将列转换为因子

时间:2015-08-19 17:34:09

标签: r dataframe

我有一个包含一些数字列,一些因子列和一些字符列的数据框。我已经创建了df作为表示。当我尝试使用“聚合”将此数据框折叠为“PO.Line”列时,它会将我的所有列转换为因子。这是为什么?

作为旁注,如果我的数据框不包含Customer.Name列,则聚合似乎可以正常工作。

df
  Order.Number PO.Line Unit.Selling.Price       Agreement Shipped Customer.Name
1            1     A_1                 10                       1           One
2            3     A_1                  0                      NA           two
3            4     A_2                 15 Platinum Member      NA          bill
4            7     A_2                  0                       1       craster
5            8     B_3                 12                       3       marilyn

str(df)
# 'data.frame':   5 obs. of  6 variables:
# $ Order.Number      : num  1 3 4 7 8
# $ PO.Line           : Factor w/ 3 levels "A_1","A_2","B_3": 1 1 2 2 3
# $ Unit.Selling.Price: num  10 0 15 0 12
# $ Agreement         : Factor w/ 2 levels "","Platinum Member": 1 1 2 1 1
# $ Shipped           : num  1 NA NA 1 3
# $ Customer.Name     : chr  "One" "two" "bill" "craster" ...

str(aggregate(. ~ PO.Line, data = df, head, 1))
# 'data.frame':   3 obs. of  6 variables:
#  $ PO.Line           : Factor w/ 3 levels "A_1","A_2","B_3": 1 2 3
#  $ Order.Number      : Factor w/ 3 levels "1","7","8": 1 2 3
#  $ Unit.Selling.Price: Factor w/ 3 levels "0","10","12": 2 1 3
#  $ Agreement         : Factor w/ 1 level "1": 1 1 1
#  $ Shipped           : Factor w/ 2 levels "1","3": 1 1 2
#  $ Customer.Name     : Factor w/ 3 levels "craster","marilyn",..: 3 1 2

df$Customer.Name <- NULL
str(aggregate(. ~ PO.Line, data = df, head, 1))
# 'data.frame':   3 obs. of  5 variables:
#  $ PO.Line           : Factor w/ 3 levels "A_1","A_2","B_3": 1 2 3
#  $ Order.Number      : num  1 7 8
#  $ Unit.Selling.Price: num  10 0 12
#  $ Agreement         : num  1 1 1
#  $ Shipped           : num  1 1 3

0 个答案:

没有答案