r - 通过 Apply 嵌套多个函数

r - Nesting multiple Functions via Apply

我想使用 is.na 和求和来查找类似于 mtcars 的数据集中缺失值的数量。

这是我的代码:

x <- apply(mtcars, 2, is.na)
y <- apply(x, 2, sum)

然而,这很丑陋。他们的方法是否相当于:

z <- apply(mtcars, 2, sum(is.na))

使用 lamdba 表达式(function(x) 或 shorthand(R 4.1.0 中的\(x)

apply(mtcars, 2, \(x) sum(is.na(x)))
  mpg  cyl disp   hp drat   wt qsec   vs   am gear carb 
   0    0    0    0    0    0    0    0    0    0    0 

在将 data.frame 转换为逻辑 matrix 之后,也可以使用矢量化 colSums 执行此操作(is.na - 因为 methods('is.na') 也包括一个 data.frame 特定方法)

colSums(is.na(mtcars))
  mpg  cyl disp   hp drat   wt qsec   vs   am gear carb 
   0    0    0    0    0    0    0    0    0    0    0 

OP 可能想要 compose 多个函数

library(purrr)
apply(mtcars, 2, compose(sum, is.na))
 mpg  cyl disp   hp drat   wt qsec   vs   am gear carb 
   0    0    0    0    0    0    0    0    0    0    0 

默认情况下 .dir 是“向后”。我们可以通过指定

来覆盖它
apply(mtcars, 2, compose(is.na, sum, .dir = "forward"))
   mpg  cyl disp   hp drat   wt qsec   vs   am gear carb 
   0    0    0    0    0    0    0    0    0    0    0 

如果你真的想用apply,你可以试试这个

apply(is.na(mtcars), 2, sum)

但是, 提供了一种更有效的方法来实现相同的目标,强烈推荐!