【发布时间】:2021-10-21 22:28:55
【问题描述】:
我想使用purrr 将许多因子变量转换为二分变量。这是我正在尝试完成的示例,使用带有改编自 this answer 的函数的玩具数据集:
library(dplyr)
library(forcats)
library(tidyr)
library(purrr)
df <- tibble(a = c(1,2,3),
b = c(1,1,2),
c = as_factor(c("Rose","Pink","Red")),
d = c(2,3,4),
e = as_factor(c("Paris", "London", "Paris"))
)
fac_to_d <- function(.data, col) {
.data %>%
mutate(value = 1) %>%
pivot_wider(names_from = {{col}},
values_from = value,
values_fill = 0)
}
该功能有效:
df %>%
fac_to_d("c") %>%
fac_to_d("e")
#> # A tibble: 3 × 8
#> a b d Rose Pink Red Paris London
#> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
#> 1 1 1 2 1 0 0 1 0
#> 2 2 1 3 0 1 0 0 1
#> 3 3 2 4 0 0 1 1 0
但我不知道如何使它与purrr 一起工作。例如:
cols <- c("c", "e")
df %>% map_dfr(.f = fac_to_d, col = cols)
#> Error in UseMethod("mutate"): no applicable method for 'mutate' applied to an object of class "c('double', 'numeric')"
df %>% map(.f = fac_to_d, col = cols)
#> Error in UseMethod("mutate"): no applicable method for 'mutate' applied to an object of class "c('double', 'numeric')"
如何让这个函数与purrr 一起工作? (如果有更好的方法将许多因子变量转换为二分变量,我也有兴趣了解这一点!)
【问题讨论】:
-
嗯,我认为在您的方法中,您希望循环通过
cols而不是df。但是,这并不完全有效,因为看起来您每次都想更新df,就像在管道链中直接使用fac_to_d()一样。如果您使用map()循环,您将首先在数据集中保留“e”的虚拟“c”,然后仍在数据集中保留“c”的虚拟“e”。