仅对 r 数据表中具有数值的列运行函数

Jac*_*one 1 r data.table

我想运行以下函数

count_greater_than <- function(x){
  ret <- sum(x > 1);
  return(ret);
}
Run Code Online (Sandbox Code Playgroud)

将虹膜数据集作为数据表。但是,我只想对 iris 中具有数值的所有列(除“物种”之外的所有列)运行该函数。我的方法是

dt <- as.data.table(iris);
gr_1 <- dt[, sapply(.SD,count_greater_than, is.numeric)];
names(gr_1) <- colnames(iris);
gr_1;
Run Code Online (Sandbox Code Playgroud)

这给了我;

Sepal.Length  Sepal.Width Petal.Length  Petal.Width      Species 
         150          150          149           93           NA 
Run Code Online (Sandbox Code Playgroud)

但我想要的是;

Sepal.Length  Sepal.Width Petal.Length  Petal.Width 
150          150          149           93 
Run Code Online (Sandbox Code Playgroud)

有没有办法排除具有非数字值的列?或者至少指定我想要涵盖的列?

Ron*_*hah 6

您可以使用.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
Run Code Online (Sandbox Code Playgroud)

等价于dplyr

library(dplyr)
dt %>% summarise(across(where(is.numeric), count_greater_than))
Run Code Online (Sandbox Code Playgroud)

  • 在开发版本 1.12.9 中: `.SDcols=is.numeric` 现在可以工作;即,“SDcols=”接受一个用于选择“.SD”列的函数,请参阅[此处](https://rdatatable.gitlab.io/data.table/news/index.html)。 (4认同)