r - r - 通过 Apply 嵌套多个函数
问题描述
我想使用 is.na 和 sum 在类似于 mtcars 的数据集中查找缺失值的数量。
这是我的代码:
x <- apply(mtcars, 2, is.na)
y <- apply(x, 2, sum)
然而,这很丑陋。他们的方法是否等同于:
z <- apply(mtcars, 2, sum(is.na))
解决方案
使用 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 转换为逻辑后,也可以使用矢量化来执行此操作matrix
(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
推荐阅读
- ios - 如何防止由于 TableView 中未捕获的异常“CALayerInvalid”错误而终止应用程序
- excel - 使用 Excel VBA 禁用特定工作表(“ply”)右键单击选项
- visual-studio - AVX512 和 MSVC 预处理器符号
- javascript - 如何在Vue中设置当前年份加上未来5年的数组?
- ms-access-2007 - 使用带有复选框的表单输入进行查询
- javascript - 将值从预定义列表链接到数据参数的问题
- r - R:对于第 [i] 行中的新变量,比较列 x 和 y 中的行综合
- google-chrome - 支持或弃用 URL 中的 HTTP 基本身份验证
- python - 在集成的 PyCharm jupyter notebook 中获取正确的数据帧输出
- javascript - 在数组中查找最常见的字符串失败,有 2 个元素或相等数量