【问题标题】:Drop levels of the same name from the whole dataframe从整个数据框中删除同名级别
【发布时间】:2018-06-06 02:36:15
【问题描述】:

在数据框中的单个因素中删除一个级别很容易,基础 R 和各种包提供了几种方法来做到这一点。但是有没有办法从数据框中的多个因素中删除具有相同名称的级别?

例如,在数据框DF 中,有没有办法从V1V2 中删除级别D

DF <- data.frame(V1 = factor(c("A", "B", "C", "A", "D", "E")),
                 V2=factor(c("A", "A", "A", "A", "D", "E")))

【问题讨论】:

    标签: r dataframe


    【解决方案1】:

    这是一个从数据框中的所有因子中删除特定因子水平的示例。

    DF <- data.frame(V1 = factor(c("A", "B", "C", "A", "D", "E")),
                     V2=factor(c("A", "A", "A", "A", "D", "E")))
    
    dropLevels <- function(col, value){
         if(is.factor(col)){
              droplevels(col, value)
         }else{col}
    }
    
    
    DF %>% purrr::modify(~ dropLevels(., "D")) 
    

    【讨论】:

      【解决方案2】:

      您可以使用mapplydroplevels,但是,您需要再次考虑变量。

      mapply(DF, FUN = function(x) droplevels(x, "D")) 
      
           V1  V2 
      [1,] "A" "A"
      [2,] "B" "A"
      [3,] "C" "A"
      [4,] "A" "A"
      [5,] NA  NA 
      [6,] "E" "E"
      

      【讨论】:

      • 谢谢。这行得通,但我认为@TBT8 的回答更直接。
      • 谢谢你,很高兴我能帮上忙。 @TVT8 的回答确实更直接一些。我也给了他一票:)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-09
      • 1970-01-01
      • 2017-06-27
      相关资源
      最近更新 更多