【问题标题】:Pull names of variables with a threshold of missing values提取具有缺失值阈值的变量名称
【发布时间】:2018-05-29 22:10:10
【问题描述】:

我正在处理一个包含 93 列的数据集,其中许多列有很大比例的缺失值。我正在寻找一种方法来简化筛选每一列的缺失值百分比,然后返回高于该阈值的变量名称列表以包含在新数据集中。

我有一个检查缺失值并返回缺失百分比的函数:

#check for missing data
pMiss <- function(x) {
  sum(is.na(x))/length(x)*100
}

#percent of data missing per column
x <- apply(dt2,2,pMiss)

如何检索缺失值百分比小于 20% 的列的所有名称 [来自 x]?我想将这些名称检索为可以粘贴到新数据集中的列表,因此我不必手动复制和粘贴 x.xml 中的每个名称。

提前谢谢你。

【问题讨论】:

    标签: r function missing-data


    【解决方案1】:

    这会起作用的:

    # example dataset
    set.seed(123)
    dat <- data.frame(a=sample(c(1,2,NA), size=20, replace=TRUE), 
                      b=sample(c(1,2,NA), size=20, replace=TRUE), 
                      c=sample(c(1:10,NA), size=20, replace=TRUE))
    
    threshold <- .25 # for example
    
    # get subset of colnames s.t. NA proportion is greater than threshold
    names(dat)[sapply(dat, function(x) mean(is.na(x)) > threshold)]
    ## [1] "a" "b"
    

    【讨论】:

      【解决方案2】:

      您可以使用tidyverse 方法:

      require(tidyverse)
      set.seed(123)
      dat <- data.frame(a=sample(c(1,2,NA), size=20, replace=TRUE), 
                        b=sample(c(1,2,NA), size=20, replace=TRUE), 
                        c=sample(c(1:10,NA), size=20, replace=TRUE))
      
      threshold <- .43 
      
      dat %>% 
        gather(var, value) %>% 
        group_by(var) %>% 
        summarise(prep.missing = sum(is.na(value)) / n()) %>% 
        filter(prep.missing < threshold)
      
        var   prep.missing
        <chr>        <dbl>
      1 a            0.400
      2 c            0. 
      

      【讨论】:

      • 谢谢!非常有帮助
      【解决方案3】:
      df <- data.frame(a=c(NA,NA,1,1),b=c(NA,1,1,1),c=c(1,1,1,1))
      x <- colMeans(is.na(df))
      # a    b    c 
      # 0.50 0.25 0.00
      
      x[x < .3]
      # b    c 
      # 0.25 0.00
      
      names(x[x < .3])
      # [1] "b" "c"
      

      或全部在一行中:

      names(df)[colMeans(is.na(df)) < .3]
      # [1] "b" "c"
      

      【讨论】:

      • 非常感谢!
      猜你喜欢
      • 2018-11-25
      • 1970-01-01
      • 1970-01-01
      • 2021-06-28
      • 1970-01-01
      • 1970-01-01
      • 2020-03-19
      • 2017-05-25
      • 1970-01-01
      相关资源
      最近更新 更多