首页 > 解决方案 > r - 通过 Apply 嵌套多个函数

问题描述

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

这是我的代码:

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

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

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

标签: rnestedapply

解决方案


使用 lamdba 表达式(或者function(x)简写形式(\(x)from R 4.1.0

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 

colSums在将 data.frame 转换为逻辑后,也可以使用矢量化来执行此操作matrixis.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 

推荐阅读