dplyr使用变量列进行mutate

8

我正在尝试使用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))

我希望能实现以下功能:

我想要做类似这样的事情:

x %>% mutate(new_col = col_to_use)

除了列的内容,我想将它们转换为变量。我从以下开始: ```python ```
col_name = "colA"
x %>% mutate(new_col = !!as.name(col_name))

这个问题需要使用静态变量来解决。然而,我一直无法改变变量以表示列名。如何根据另一列的内容获取列名?

这个问题基本上与这个相反:dplyr - mutate: use dynamic variable names。我没能够将解决方案适应到我的问题上。

2个回答

5
我们可以使用包中的imap_dblpluck来完成这个任务。
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.

3

我不确定仅使用tidyverse习语如何完成它(尽管我认为有一种方法)。但是这里是一种使用apply的方法:

x$new_col = apply(x, 1, function(d) {
  d[match(d["col_to_use"], names(x))]
})
  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))]
  }))

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接