dplyr NSE - 如何将列名传递给mutate函数调用?

时间:2017-09-18 19:18:11

标签: r dplyr tidyverse nse mutate

我想在变量中指定的列上使用gsub参数来改变数据框的列,但我正在努力进行非标准评估。

在这个玩具示例中,我希望在调用gsub时使用columns[[1]]columns[[2]]代替.$name_A.$name_B。我可以,还是需要重新考虑我的方法?

library(tidyverse)

test_df <- tibble(name_A = 
                   c("asdf", "ghjk"),
                 name_B =
                   c("qwer", "tyui"))

columns <- c("name_A", "name_B")

test_df %>%
  mutate(new_col_A = 
           gsub(pattern = 'asdf', replacement = 'NEW_VALUE_A', x = .$name_A),
         new_col_B = 
           gsub(pattern = 'tyui', replacement = 'NEW_VALUE_B', x = .$name_B))

2 个答案:

答案 0 :(得分:2)

你快到了。您可以使用rlang::syms!!来执行您需要的操作。

library(tidyverse)

test_df <- tibble(name_A = 
                    c("asdf", "ghjk"),
                  name_B =
                    c("qwer", "tyui"))

columns <- rlang::syms(c("name_A", "name_B"))

test_df %>%
  mutate(new_col_A = 
           gsub(pattern = 'asdf', replacement = 'NEW_VALUE_A', x = !! columns[[1]]),
         new_col_B = 
           gsub(pattern = 'tyui', replacement = 'NEW_VALUE_B', x = !! columns[[2]]))

答案 1 :(得分:0)

我不是100%确定你在问什么,但你可以使用正则表达式使用mutate_atmatches将mutate应用于列:

library(tidyverse)

test_df %>% 
  mutate_at(vars(matches('A')), 
            function(.x) gsub(pattern = 'asdf', 
                              replacement = 'NEW_VALUE_A', .x)) %>% 
  mutate_at(vars(matches('B')), 
            function(.x) gsub(pattern = 'tyui', 
                         replacement = 'NEW_VALUE_B', .x))

希望有所帮助!

编辑 - 你也可以通过索引来调用:

test_df %>% 
mutate_at(vars(1), 
          function(.x) gsub(pattern = 'asdf',
                            replacement = 'NEW_VALUE_A', .x)) %>%
mutate_at(vars(2),
          function(.x) gsub(pattern = 'tyui',
                            replacement = 'NEW_VALUE_B', .x))