r - 仅在 r 的数据表中对具有数值的列运行函数
问题描述
我想运行以下功能
count_greater_than <- function(x){
ret <- sum(x > 1);
return(ret);
}
将 iris 数据集作为数据表。但是,我只想为 iris 中具有数值的所有列(除“物种”之外的所有列)运行该函数。我的方法是
dt <- as.data.table(iris);
gr_1 <- dt[, sapply(.SD,count_greater_than, is.numeric)];
names(gr_1) <- colnames(iris);
gr_1;
这给了我;
Sepal.Length Sepal.Width Petal.Length Petal.Width Species
150 150 149 93 NA
但我想要的是;
Sepal.Length Sepal.Width Petal.Length Petal.Width
150 150 149 93
有没有办法排除具有非数字值的列?或者至少指定我想要涵盖的列?
解决方案
您可以使用.SDcols
指定要应用该函数的列。
library(data.table)
dt[, lapply(.SD, count_greater_than), .SDcols = sapply(dt, is.numeric)]
# Sepal.Length Sepal.Width Petal.Length Petal.Width
#1: 150 150 149 93
中的等价物dplyr
是:
library(dplyr)
dt %>% summarise_if(is.numeric, count_greater_than)
推荐阅读
- ansible - jinja2 模板中的 Ansible 变量
- c# - Rider 终端/控制台未清除 [Linux/C#]
- bazel - 有没有一种简单的方法可以查看 Bazel“Make”变量扩展到什么?
- c# - Unity AI 角色控制器重力
- haskell - haskell 函数,它接受一个整数并以二进制形式返回表示该数字的字符串
- distributed-computing - 在(CAP)一致性与可访问性问题期间,哪些类型的数据会丢失?
- javascript - javascript - 如何仅在画布边框内绘制
- flutter - 如何在 Flutter 的 CircleAvatar 中控制图像大小?
- c# - 传入字典的模型项是“类”类型的,但是这个字典需要一个 ienumarator 类型的模型项
- python - 遍历数独子网格以检查特定值