在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]])
                                           }
                               }
                         }

实现这一目标的另一种方式是什么,希望更简洁?

回答

这是一种使用tidyverse.

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

  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

  • Despite their use of "binary" a couple times, the only check OP is attempting in the question is the `n_distinct`. The "binary" columns may just be an example.
  • Though you've explained your steps well enough that they should be able to adapt as needed.

以上是在R中,如何将数据框中的许多选择(二进制)列更改为因子?的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>