首页 > 解决方案 > 使用 purrr 和 select 创建二分变量

问题描述

我正在尝试根据所选连续变量的存在(或不存在)创建二分变量列。

例子:

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))

但是我的实际用例涉及很多变量,所以我想使用purrrand dplyr::select。我尝试了很多方法,例如:

out <- df %>% 
  select(starts_with("a_")) %>% 
  map(.x, .f = mutate({{.x}}_d = 
                        if_else(is.na(.x), 0, 1)))

但我认为我遗漏了一些关于名称分配map和将变量传递到map. df从使用函数到out使用purrr函数的最有效方法是什么dplyr::select

标签: rdplyrpurrr

解决方案


你觉mutate()得怎么样across()?这似乎是解决此类问题的好工具。

您可以使用整洁的选择功能选择要“跨越”哪些列,就像在select(). 然后我们给出我们想要在每一列上使用的函数。你会看到我as.numeric()在“not NA”(!is.na)的逻辑输出上使用了 0/1,但你也可以if_else()在这里使用。我在函数中使用了purrr样式的 lambda(即 ~)。

要为要添加到数据集的新列添加后缀,我对.fns.

mutate(df, across(.cols = starts_with("a"),
                  .fns = list(d = ~as.numeric(!is.na(.x)))))
#> # A tibble: 2 x 5
#>       z   a_1   a_2 a_1_d a_2_d
#>   <dbl> <dbl> <dbl> <dbl> <dbl>
#> 1     0   0.1  NA       1     0
#> 2     0  NA     0.1     0     1

reprex 包于 2021-11-03 创建 (v2.0.0 )


推荐阅读