【问题标题】:best way to perform fct_lump on multiple columns [duplicate]在多列上执行 fct_lump 的最佳方法 [重复]
【发布时间】:2023-03-12 06:35:01
【问题描述】:

我想将具有多个变量的因子变量的不常见级别集中到“其他”中。我试图重现下面的问题。动物和颜色是我想综合起来的两个因素变量。当我将它们放入列表并遍历列表时,它不起作用。但它适用于一个变量。我的实际数据集有几十个这样的变量,我想用 dplyr 方法找到一种干净的方法。

library(tidyverse)
library(forcats)

data <- data.frame(ID=rep(1:12), animal=c('dog','cat','fish','dog','dog','dog','fish','fish','fish','snake','fish','dog'),color=c('red','green','blue','red','green',
                                          'red','green','red','green','red','green','red'))

### Does not work when I use a list and for loop

factor_columns <- c('animal','color')
for (feature in factor_columns) {
  data <- data %>%
    mutate(feature = fct_lump_prop(
      f = feature,
      prop = 0.2,
      other_level = 'other'
    ))} 

### Works with one column

data <- data %>%
  mutate(animal = fct_lump_prop(
    f = animal,
    prop = 0.2,
    other_level = 'other'
  )) 

【问题讨论】:

    标签: r


    【解决方案1】:

    您可以使用across

    library(dplyr)
    library(forcats)
    
    data %>%
      mutate(across(factor_columns, fct_lump_prop,prop = 0.2,other_level = 'other'))
      #mutate_at in old dplyr
      #mutate_at(vars(factor_columns), fct_lump_prop,prop = 0.2,other_level = 'other')
    

    你也可以使用lapply

    data[factor_columns] <- lapply(data[factor_columns], 
                             fct_lump_prop,prop = 0.2,other_level = 'other')
    

    【讨论】:

    • 完美运行。谢谢!
    猜你喜欢
    • 2011-08-28
    • 2020-09-12
    • 2017-11-07
    • 2021-09-06
    • 1970-01-01
    • 1970-01-01
    • 2018-11-29
    • 2018-03-13
    • 2018-03-24
    相关资源
    最近更新 更多