我有一个包含许多列的数据集,我想找到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]])
}
}
}
Run Code Online (Sandbox Code Playgroud)
实现这一目标的另一种方式是什么,希望更简洁?
这是一种使用tidyverse.
我们可以利用whereinsideacross来选择我们检查的具有逻辑短路表达式的列
numeric- ( is.numeric)all的unique元素是 0 和 1factor类library(dplyr)
df1 <- df %>%
mutate(across(where(~is.numeric(.) &&
n_distinct(.) < n &&
all(unique(.) %in% c(0, 1))), factor))
Run Code Online (Sandbox Code Playgroud)
-检查
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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
60 次 |
| 最近记录: |