【问题标题】:Return top 20% highest value in a column into 1 and make the rest of the numbers 0将列中前 20% 的最高值返回为 1,并将其余数字设为 0
【发布时间】:2021-10-10 09:28:51
【问题描述】:

将列中前 20% 的最高值返回为 1,其余数字为 0

DF

dat1 = data.frame(a = c(0.1,0.2,0.3,0.4,0.5), b = c(0.6,0.7,0.8,0.9,0.10), c = c(0.12,0.13,0.14,0.15,0.16), d = c(0.6,0.7,0.8,0.5,0.9), ID=c("Albert", "Bia", "Carla", "Duda", "Elisa"))

想要的 DF

dat1 = data.frame(a = c(0,0,0,0,1), b = c(0,0,0,1,0), c = c(0,0,0,0,1), d = c(0,0,0,0,1), ID=c("Albert", "Bia", "Carla", "Duda", "Elisa"))

【问题讨论】:

    标签: r dataframe subset data-cleaning


    【解决方案1】:

    或使用colQuantiles

    library(matrixStats)
    dat1[1:4] <- +(dat1[1:4] >colQuantiles(as.matrix(dat1[1:4])))
    

    【讨论】:

      【解决方案2】:

      您可以在dplyr 中使用across -

      library(dplyr)
      
      dat1 %>% mutate(across(a:d, ~as.integer(. > quantile(., 0.8))))
      
      #  a b c d     ID
      #1 0 0 0 0 Albert
      #2 0 0 0 0    Bia
      #3 0 0 0 0  Carla
      #4 0 1 0 0   Duda
      #5 1 0 1 1  Elisa
      

      【讨论】:

        【解决方案3】:

        使用apllyquantile

        dat1[,1:4] <- apply(dat1[,1:4], 2, function(x) ifelse(x>=quantile(x, probs = c(0.8, 1))[2],1,0))
        
        output:
        > dat1
          a b c d     ID
        1 0 0 0 0 Albert
        2 0 0 0 0    Bia
        3 0 0 0 0  Carla
        4 0 1 0 0   Duda
        5 1 0 1 1  Elisa
        

        【讨论】:

        • 你可以缩短它:apply(dat1[,1:4], 2, function(x) ifelse(x&gt;=quantile(x, 0.8),1,0))
        • 谢谢!你能解释一下为什么是数字“2”吗?
        • couse probs = c(0.8, 1) 给你 2 个分位数。你想用第二个。
        • @Fernanda 如果您指的是应用中的“2”:它代表第二维,这里是列。如果您改用“1”,则将函数应用于行。
        • 谢谢你,佐伊!
        猜你喜欢
        • 1970-01-01
        • 2018-11-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-09-01
        • 1970-01-01
        • 2021-08-18
        • 2018-11-25
        相关资源
        最近更新 更多