搜索具有严格0/1数据的变量,并在R和dplyr/tidyverse/pipe中使用Yes/No将其转换为因子

bxjv4tth  于 2022-12-20  发布在  其他
关注(0)|答案(1)|浏览(98)

我有

df <- data.frame(
  var1 = c(0, 1, 0, 1, 1, 0, 1),
  var2 = c("1", "1", "0", "0", "1", "1", "0"),
  var3 = c("1", "1", "0", "0", "1", "3", "1"),
  var4 = c(0, 0, 1, 1, 1, 0, 3),
  var5 = c("Yes", "No", "Yes", "No", "Yes", "No", "Yes"),
  var6 = c("Yes", "No", "Yes", "No", "Yes", "No", "Maybe")
)

我想搜索具有严格0/1值的所有变量,并将它们转换为具有"No"/"Yes"标签的因子。
我的尝试是

df %>%
  mutate(across(where(unique(.) == c("0", "1")), 
                .fns = ~factor(ifelse(., "Yes", "No"), levels = c("Yes", "No"))))

但似乎不起作用。

Error in `mutate()`:
! Problem while computing `..1 = across(...)`.
Caused by error in `across()`:
! Problem while evaluating `where(unique(.) == c("0", "1"))`.
Caused by error in `where()`:
! Can't convert `fn`, a logical matrix, to a function.

我在tidyverse/dplyrpipe系统中寻找解决方案。我不想指定要搜索或转换的变量。
在上面的示例中,只应转换var1var2

k4ymrczo

k4ymrczo1#

您应该能够做到:

library(dplyr)

df %>%
  mutate(across(where(~ all(.x %in% 0:1)), factor, labels = c("No", "Yes")))

  var1 var2 var3 var4 var5  var6
1   No  Yes    1    0  Yes   Yes
2  Yes  Yes    1    0   No    No
3   No   No    0    1  Yes   Yes
4  Yes   No    0    1   No    No
5  Yes  Yes    1    1  Yes   Yes
6   No  Yes    3    0   No    No
7  Yes   No    1    3  Yes Maybe

相关问题