【问题标题】:Delete columns with several zeros删除有多个零的列
【发布时间】:2021-10-06 09:42:57
【问题描述】:

我需要删除所有超过 1 个零的列。我目前正在使用df <- df[, colSums(df != 0) > 1],但这不适用于所有具有许多零的列。如何解决这个问题或以不同的方式解决这个问题?

> tibble(df)
# A tibble: 551 x 1,046
            `aa`           `ab`           `ac`         `ad`         `ae`         `af` 
            <dbl>          <dbl>          <dbl>        <dbl>        <dbl>        <dbl>        
 1          32458          65068          32654        0            43115         1450         
 2          19387          38457          19447        0            22523          958         
 3          42690          85105          43247        0            14156         1088         
 4          62290         123325          61878        58422        36300         1145  

【问题讨论】:

    标签: r dataframe filtering


    【解决方案1】:

    我们可以使用select 来选择逻辑表达式的mean 的列,即那些为0 的元素小于0.7

    library(dplyr)
    df %>%
        select(where(~ mean(. %in% 0) < 0.7))
    

    -输出

        aa     ab    ac    ae   af
    1 32458  65068 32654 43115 1450
    2 19387  38457 19447 22523  958
    3 42690  85105 43247 14156 1088
    4 62290 123325 61878 36300 1145
    

    如果是删除零值超过1个的列

    df %>%
       select(where( ~sum(. %in% 0) < 2))
    

    -输出

       aa     ab    ac    ae   af
    1 32458  65068 32654 43115 1450
    2 19387  38457 19447 22523  958
    3 42690  85105 43247 14156 1088
    4 62290 123325 61878 36300 1145
    

    base R中的类似选项

     Filter(function(x) mean(x %in% 0) < 0.7, df)
         aa     ab    ac    ae   af
    1 32458  65068 32654 43115 1450
    2 19387  38457 19447 22523  958
    3 42690  85105 43247 14156 1088
    4 62290 123325 61878 36300 1145
    

    或使用sum 进行零计数

    Filter(function(x) sum(x %in% 0) < 2, df)
    

    数据

    df <- structure(list(aa = c(32458L, 19387L, 42690L, 62290L), ab = c(65068L, 
    38457L, 85105L, 123325L), ac = c(32654L, 19447L, 43247L, 61878L
    ), ad = c(0L, 0L, 0L, 58422L), ae = c(43115L, 22523L, 14156L, 
    36300L), af = c(1450L, 958L, 1088L, 1145L)),
     class = "data.frame", row.names = c("1", 
    "2", "3", "4"))
    

    【讨论】:

    • 我的目标是删除超过 1 个零的列,但我尝试了上述方法,但它不起作用
    • @aurelius_37809 但你的描述是 70% 0
    • 对不起,如果这有误导性,我只是在描述df的特征
    【解决方案2】:

    也许你可以试试下面的colMeans

    df[colMeans(df == 0) < 0.7]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-08-01
      • 1970-01-01
      • 2023-03-17
      • 1970-01-01
      • 2019-12-09
      • 2014-04-01
      • 1970-01-01
      相关资源
      最近更新 更多