【问题标题】:Check whether any column in the dataframe only has two unique values NA and 0检查数据框中的任何列是否只有两个唯一值 NA 和 0
【发布时间】:2021-10-17 06:59:08
【问题描述】:

我有一个数据框,其中某些列仅包含值 0 和 NA。我可以找到是否有任何具有 2 个唯一值的列。但是如何检查数据框中是否有只有 0 和 NA 的列?

apply(production_list_DF, 2, function(a) length(unique(a))==2) 

这只是检查每列是否只有 2 个唯一值

【问题讨论】:

    标签: r


    【解决方案1】:

    这行得通吗:

    set.seed(1)
    df <- data.frame(col1 = sample(1:10,5,F),
                     col2 = sample(1:10,5,F),
                     col3 = sample(c(NA,0),5,T),
                     col4 = sample(c(NA,0),5,T))
    
    df
      col1 col2 col3 col4
    1    9    7   NA    0
    2    4    2   NA   NA
    3    7    3    0   NA
    4    1    8    0   NA
    5    2    1    0   NA
    
    apply(df,2,function(x) all(x %in% c(NA,0)))
     col1  col2  col3  col4 
    FALSE FALSE  TRUE  TRUE 
    

    获取列名

    names(df[apply(df,2,function(x) all(x %in% c(NA,0)))])
    [1] "col3" "col4"
    

    使用 sapply:

    sapply(df, function(x) all(x %in% c(NA,0)))
     col1  col2  col3  col4 
    FALSE FALSE  TRUE  TRUE 
    names(df[sapply(df, function(x) all(x %in% c(NA,0)))])
    [1] "col3" "col4"
    

    【讨论】:

      【解决方案2】:

      基础 R 解决方案:

      我更喜欢colSumssapply

      > colSums(sapply(df, `%in%`, c(0, NA))) == nrow(df)
       col1  col2  col3  col4 
      FALSE FALSE  TRUE  TRUE 
      > 
      

      或者用一个函数:

      > sapply(df, function(x) all(x %in% c(NA, 0)))
       col1  col2  col3  col4 
      FALSE FALSE  TRUE  TRUE 
      > 
      

      来自@KarthikS 的示例数据框:

      set.seed(1)
      df <- data.frame(col1 = sample(1:10,5,F),
                       col2 = sample(1:10,5,F),
                       col3 = sample(c(NA,0),5,T),
                       col4 = sample(c(NA,0),5,T))
      
      df
        col1 col2 col3 col4
      1    9    7   NA    0
      2    4    2   NA   NA
      3    7    3    0   NA
      4    1    8    0   NA
      5    2    1    0   NA
      

      对于列名:

      > names(df)[colSums(sapply(df, `%in%`, c(0, NA))) == nrow(df)]
      [1] "col3" "col4"
      > 
      

      或者:

      > names(df)[sapply(df, function(x) all(x %in% c(NA, 0)))]
      [1] "col3" "col4"
      > 
      

      附注在此处的所有示例中,sapply 都可以替换为 apply(df, 2, ...)

      【讨论】:

        猜你喜欢
        • 2020-04-30
        • 1970-01-01
        • 1970-01-01
        • 2019-11-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多