dplyr使用可变列进行突变 [英] dplyr mutate using variable columns
问题描述
我正在尝试使用mutate
创建一个具有基于特定列的值的新列.
I am trying to use mutate
to create a new column with values based on a specific column.
示例最终数据帧(我正在尝试创建new_col
):
Example final data frame (I am trying to create 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))
我想做类似的事情:
x %>% mutate(new_col = col_to_use)
除了列内容以外,我想将它们转换为变量.我开始:
Except instead of column contents, I would like to transform them to a variable. I started with:
col_name = "colA"
x %>% mutate(new_col = !!as.name(col_name))
与静态变量一起使用.但是,我一直无法更改代表列的变量.如何根据其他列的内容获取列名?
That works with a static variable. However, I have been unable to change the variable to represent the column. How do I take a column name based on contents of a different column?
这个问题基本上是相反的: dplyr-mutate:使用动态变量名.我无法使解决方案适应我的问题.
This question is basically the opposite of this: dplyr - mutate: use dynamic variable names. I wasn't able to adapt the solution to my problem.
推荐答案
我们可以使用 purrr 包即可完成此任务.
We can use imap_dbl
and pluck
from the purrr package to achieve this task.
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.
这篇关于dplyr使用可变列进行突变的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!