R中的聚合 – na.omit和na.pass与因子(逐个因子)?

我有一个包含工资测试数据的数据集.并非所有单元格都有值,因此我使用na.action = na.pass,na.rm = TRUE但由于我想与JobTitle聚合这是因素,它给了我一个错误?

到目前为止,我开发了以下代码:

aggregate(salaries$JobTitle, 
list(pay = salaries$TotalPay),
FUN=mean,
na.action=na.pass,
na.rm=TRUE)

我的测试数据包含以下列:

'data.frame':   104 obs. of  36 variables:
 $Id              : int  1 2 3 4 5 6 7 8 9 10 ...
 $EmployeeName    : Factor w/ 11 levels "","ALBERT PARDINI",..: 10 7 2 4 11 6 3 5 9 8 ...
 $JobTitle        : Factor w/ 9 levels "","ASSISTANT DEPUTY CHIEF II",..: 8 4 4 9 6 2 3 7 3 5 ...
 $BasePay         : num  167411 155966 212739 77916 134402 ...
 $OvertimePay     : num  0 245132 106088 56121 9737 ...
 $OtherPay        : num  400184 137811 16453 198307 182235 ...
 $Benefits        : logi  NA NA NA NA NA NA ...
 $TotalPay        : num  567595 538909 335280 332344 326373 ...
 $TotalPayBenefits: num  567595 538909 335280 332344 326373 ...
 $Year            : int  2011 2011 2011 2011 2011 2011 2011 2011 2011 2011 ...
 $Notes           : logi  NA NA NA NA NA NA ...
 $Agency          : Factor w/ 2 levels "","San Francisco": 2 2 2 2 2 2 2 2 2 2 ..

出现的错误代码是

Warning messages:
1: In mean.default(X[[i]], ...) :
  argument is not numeric or logical: returning NA
2: In mean.default(X[[i]], ...) :
  argument is not numeric or logical: returning NA

等等…

我已经尝试过工资$Id并且它像魔术一样工作,所以我假设代码是正确的,也许我需要更改JobTitle的数据类型?

最佳答案 如果我们得到’TotalPaygrouped”JobTitle’的平均值,那么theformula`方法就是

aggregate(TotalPay~JobTitle, salaries, mean, na.rm=TRUE, na.action=na.pass)

或者使用

aggregate(salaries$TotalPay, list(salaries$JobTitle), FUN=mean, na.rm=TRUE) 

数据

set.seed(24)
salaries <- data.frame(JobTitle = sample(LETTERS[1:5], 20,
       replace=TRUE), TotalPay= sample(c(1:20, NA), 20))
点赞