使用 purrr 和 select 创建二分变量
Using purrr and select to create dichotomous variables
我正在尝试根据所选连续变量的存在(或不存在)来创建二分变量列。
示例:
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
最有效的方法是什么?
你觉得 mutate()
和 across()
怎么样?这似乎是解决此类问题的好工具。
您可以选择使用整洁的 select 函数“跨越”哪些列,就像在 select()
中一样。然后我们给出我们想要在每一列上使用的函数。您会看到我在“非 NA”(!is.na
) 的逻辑输出上使用了 as.numeric()
到 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 package (v2.0.0)
于 2021-11-03 创建
我正在尝试根据所选连续变量的存在(或不存在)来创建二分变量列。
示例:
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
最有效的方法是什么?
你觉得 mutate()
和 across()
怎么样?这似乎是解决此类问题的好工具。
您可以选择使用整洁的 select 函数“跨越”哪些列,就像在 select()
中一样。然后我们给出我们想要在每一列上使用的函数。您会看到我在“非 NA”(!is.na
) 的逻辑输出上使用了 as.numeric()
到 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 package (v2.0.0)
于 2021-11-03 创建