首页 > 解决方案 > 在 R 中,如何将数据框中的许多选择(二进制)列更改为因子?

问题描述

我有一个包含许多列的数据集,我想找到具有少于n唯一响应的列,并将这些列更改为因子。

这是我能够做到这一点的一种方法:

#create sample dataframe
df <- data.frame("number" = c(1,2.7,8,5), "binary1" = c(1,0,1,1), 
"answer" = c("Yes","No", "Yes", "No"), "binary2" = c(0,0,1,0))
n <- 3

#for each column
for (col in colnames(df)){
#check if the first entry is numeric
  if (is.numeric(df[col][1,1])){
# check that there are fewer than 3 unique values
    if ( length(unique(df[col])[,1]) < n ) {
    df[[col]] <- factor(df[[col]])
                                           }
                               }
                         }

另一种希望更简洁的方法是什么?

标签: rdataframe

解决方案


这是一种使用tidyverse.

我们可以利用wherewithinacross来选择我们检查的具有逻辑短路表达式的列

  1. 列是numeric- ( is.numeric)
  2. 如果 1 为 TRUE,则检查不同元素的数量是否小于用户定义的 n
  3. 如果 2 为 TRUE,则检查列中allunique元素是 0 和 1
  4. 遍历那些选定的列并转换为factor
library(dplyr)
df1 <- df %>% 
     mutate(across(where(~is.numeric(.) && 
                           n_distinct(.) < n && 
                           all(unique(.) %in% c(0, 1))),  factor))

-检查

str(df1)
'data.frame':   4 obs. of  4 variables:
 $ number : num  1 2.7 8 5
 $ binary1: Factor w/ 2 levels "0","1": 2 1 2 2
 $ answer : chr  "Yes" "No" "Yes" "No"
 $ binary2: Factor w/ 2 levels "0","1": 1 1 2 1

推荐阅读