r - 在 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
.
我们可以利用where
withinacross
来选择我们检查的具有逻辑短路表达式的列
- 列是
numeric
- (is.numeric
) - 如果 1 为 TRUE,则检查不同元素的数量是否小于用户定义的 n
- 如果 2 为 TRUE,则检查列中
all
的unique
元素是 0 和 1 - 遍历那些选定的列并转换为
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
推荐阅读
- javascript - 如何在 pupeteer 中模拟拖放动作
- oauth - 流明模拟/临时重新登录用户
- python - pandas read_excel 共享违规
- google-cloud-firestore - Firestore 安全规则奇怪的行为
- php - 在 laravel 中使用 composer 安装 Mailgun\Bogardo 包时出现问题
- sql-server - 如何使用 freetds 为 sphinx 配置 unixODBC 驱动程序。错误:来源:未知类型“odbc”;跳过
- php - BaseDN 语法与 LDAP 一起使用
- email - 如果请求 AD 字段为空,我如何不打印字符串
- javascript - React-bootstrap ToggleButtonGroup 在调用时使用旧值
- java - 如何在 Tensorflow 移动 Android 应用程序上使用预训练模型?