bur*_*ger 8 r dplyr nse tidyverse quosure
我正在尝试使用mutate基于特定列的值创建一个新列。
示例最终数据框(我正在尝试创建new_col):
x = tibble(colA = c(11, 12, 13),
colB = c(91, 92, 93),
col_to_use = c("colA", "colA", "colB"),
new_col = c(11, 12, 93))
Run Code Online (Sandbox Code Playgroud)
我想做类似的事情:
x %>% mutate(new_col = col_to_use)
Run Code Online (Sandbox Code Playgroud)
除了列内容之外,我想将它们转换为变量。我开始于:
col_name = "colA"
x %>% mutate(new_col = !!as.name(col_name))
Run Code Online (Sandbox Code Playgroud)
这适用于静态变量。但是,我一直无法更改变量来表示列。如何根据不同列的内容获取列名?
这个问题基本上与此相反:dplyr - mutate: use dynamic variable names。我无法根据我的问题调整解决方案。
我们可以使用imap_dbl和pluckfrom purrr包来实现这个任务。
library(tidyverse)
x <- tibble(colA = c(11, 12, 13),
colB = c(91, 92, 93),
col_to_use = c("colA", "colA", "colB"))
x2 <- x %>%
mutate(new_col = imap_dbl(col_to_use, ~pluck(x, .x, .y)))
x2
# # A tibble: 3 x 4
# colA colB col_to_use new_col
# <dbl> <dbl> <chr> <dbl>
# 1 11. 91. colA 11.
# 2 12. 92. colA 12.
# 3 13. 93. colB 93.
Run Code Online (Sandbox Code Playgroud)
我不确定如何tidyverse单独使用习语来做到这一点(尽管我认为有办法)。但这里有一个使用的方法apply:
x$new_col = apply(x, 1, function(d) {
d[match(d["col_to_use"], names(x))]
})
Run Code Online (Sandbox Code Playgroud)
Run Code Online (Sandbox Code Playgroud)colA colB col_to_use new_col 1 11 91 colA 11 2 12 92 colA 12 3 13 93 colB 93
或者,把apply里面mutate:
x = x %>%
mutate(new_col = apply(x, 1, function(d) {
d[match(d["col_to_use"], names(x))]
}))
Run Code Online (Sandbox Code Playgroud)