【问题标题】:Run function over columns with numeric values only in data table in r仅在 r 的数据表中对具有数值的列运行函数
【发布时间】:2020-03-05 02:20:05
【问题描述】:

我想运行下面的函数

count_greater_than <- function(x){
  ret <- sum(x > 1);
  return(ret);
}

把鸢尾花数据集作为数据表。但是,我只想为 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 

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

【问题讨论】:

    标签: r data.table


    【解决方案1】:

    您可以使用.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)
    

    【讨论】:

    • 在开发版本 1.12.9 中:.SDcols=is.numeric 现在可以使用;即,SDcols= 接受一个用于选择.SD 的列的函数,参见here
    • @Wimpel 你能把这个语法和“by”结合起来吗?
    • 当然,我不明白为什么不这样做。
    【解决方案2】:

    你也可以使用 dplyr:

    iris %>% 
       as_tibble() %>% 
       select_if(is.numeric) %>% 
       group_by(.) %>% 
       summarise_all(~ sum(. > 1))
    
    # A tibble: 1 x 4
      Sepal.Length Sepal.Width Petal.Length Petal.Width
             <int>       <int>        <int>       <int>
    1          150         150          149          93
    

    【讨论】:

      【解决方案3】:

      我们可以在data.table中用if/else条件指定

      library(data.table)
      dt[, lapply(.SD, function(x) if(is.numeric(x)) count_greater_than(x) else NULL)]
      #    Sepal.Length Sepal.Width Petal.Length Petal.Width
      #1:          150         150          149          93
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-06-10
        • 1970-01-01
        • 1970-01-01
        • 2015-04-19
        • 1970-01-01
        • 1970-01-01
        • 2021-07-23
        • 1970-01-01
        相关资源
        最近更新 更多