按因子水平替换列中的值

Replace values in column by factor level

我收到了一份调查 data.frame 它们有 100 列,每列有 2 个因素 - 是或否。但是有些调查的答案是,是的!或 Nope 或 Yay 或 Nah...他们真的是或否。

我的问题是如何根据因子水平转换其他列中的所有值?例如,如果因子级别为 1,则将文本替换为 Yes else No.

我的第二个问题是,有时我会留下未使用的第 3 级,如何删除数据框中所有列中所有未使用的因子。我得到了 100 多列。

我们可以遍历列并使用 %in%

替换级别
df1[] <- lapply(df1, function(x) {
            levels(x)[levels(x) %in% c("Yes!", "Yay")] <- "Yes"
            levels(x)[levels(x) %in% c("Nope", "Nah")] <- "No"
          x
        })

要删除未使用的级别,我们可以使用 droplevels

df2 <- droplevels(df1)

但是,根据我们之前的分配,它会被处理掉。

df1
#   Col1 Col2 Col3
#1   Yes   No   No
#2   Yes  Yes   No
#3    No   No   No
#4    No   No   No
#5    No  Yes   No
#6    No   No   No
#7   Yes  Yes   No
#8    No  Yes   No
#9    No   No   No
#10  Yes  Yes   No


str(df1)
#'data.frame':   10 obs. of  3 variables:
#$ Col1: Factor w/ 2 levels "No","Yes": 2 2 1 1 1 1 2 1 1 2
#$ Col2: Factor w/ 2 levels "No","Yes": 1 2 1 1 2 1 2 2 1 2
#$ Col3: Factor w/ 1 level "No": 1 1 1 1 1 1 1 1 1 1

数据

set.seed(24)
df1 <- data.frame(Col1 = sample(c("Yes", "Yes!", "Yay", "Nope", "Nah", "No"),
         10, replace=TRUE),

               Col2 = sample(c("Yes", "Yes!", "Yay", "Nope", "Nah", "No"), 10, replace=TRUE),
               Col3 = sample(c("Nope", "Nah", "No"), 10, replace=TRUE)
             )