如何使 R 中 naiveBayes() 的公式参数通用?

How to make generic the formula parameter of naiveBayes() in R?

当我使用库 "e1071" 的函数 naiveBayes() 时,需要插入以下类型的公式:

myFormula <- myClass~ feature1 + feature2 + feature3

如果我想让它变得通用(我不知道相关数据集有多少特征)我该怎么办?我只知道 myClass 列将是最后一列,我想考虑所有其他列

您可以使用 . 动态引用所有其他列。

myFormula <- cyl ~ .
naiveBayes(myFormula, data = mtcars)



    Call:
naiveBayes.default(x = X, y = Y, laplace = laplace)

A-priori probabilities:
Y
      4       6       8 
0.34375 0.21875 0.43750 

Conditional probabilities:
   mpg
Y       [,1]     [,2]
  4 26.66364 4.509828
  6 19.74286 1.453567
  8 15.10000 2.560048

   disp
Y       [,1]     [,2]
  4 105.1364 26.87159
  6 183.3143 41.56246
  8 353.1000 67.77132

如果你想要 class 动态,你可以使用 substitute 公式并使用 evalnaiveBayes 函数调用中计算它。

dynamicNB <- function(data, class) {
  myFormula <- substitute(class ~ .)
  naiveBayes(eval(myFormula), data = data)
}

dynamicNB(class = mpg, data = mtcars)