【发布时间】: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