【发布时间】:2021-12-18 07:25:30
【问题描述】:
我正在尝试根据所选连续变量的存在(或不存在)创建二分变量列。
例子:
library(tidyverse)
df <- tibble(z = c(0, 0), a_1 = c(.1, NA), a_2 = c(NA, .1))
out <- tibble(z = c(0, 0),
a_1 = c(.1, NA),
a_2 = c(NA, .1),
a_1_d = c(1, 0),
a_2_d = c(0, 1))
我可以使用 mutate 临时执行此操作:
out <- df %>%
mutate(a_1_d = if_else(is.na(a_1), 0, 1)) %>%
mutate(a_2_d = if_else(is.na(a_2), 0, 1))
但我的实际用例涉及很多变量,所以我想使用purrr 和dplyr::select。我尝试了很多方法,例如:
out <- df %>%
select(starts_with("a_")) %>%
map(.x, .f = mutate({{.x}}_d =
if_else(is.na(.x), 0, 1)))
但我认为我缺少一些关于map 中名称分配和将变量传递给map 的组合的基本知识。使用purrr 函数和dplyr::select 从df 到out 的最有效方法是什么?
【问题讨论】: