r - 使用 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))
但是我的实际用例涉及很多变量,所以我想使用purrr
and 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
?
解决方案
你觉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 )
推荐阅读
- ruby-on-rails - 在视图上看不到来自控制器的变量 - Rails 6
- asp.net-core-mvc - 如何从 ASP.NE Core 中的查询字符串中获取 int 值
- python - 在数据框中查找特定列的平均最多 x 行数
- python - 无法在 Python 类中运行定义的函数
- python - 为什么在访问 Cython 二进制文件时有些 cdef 可以访问而有些则不能访问?
- android-studio-3.0 - 当我打开一个新活动时,这与 android studio 有关
- jquery - 单击jQuery时水平滚动不起作用
- python-3.x - Python pandas:一次不能抓取超过 100 行?
- bash - bash 脚本如何在启动时运行?
- javascript - 如何在 webpack 中将 config.js 文件作为外部文件(在运行时需要它而不是捆绑)