【问题标题】:dplyr NSE - how pass column names to mutate function call?dplyr NSE - 如何将列名传递给变异函数调用?
【发布时间】:2017-09-18 19:18:11
【问题描述】:

我想在变量中指定的列上使用 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))

【问题讨论】:

  • 您可以使用rlang::sym。查看示例here

标签: r tidyverse nse dplyr


【解决方案1】:

你快到了。你可以使用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]]))

【讨论】:

    【解决方案2】:

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

    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))
    

    【讨论】:

      猜你喜欢
      • 2017-09-12
      • 2019-07-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-18
      • 2015-11-21
      • 1970-01-01
      相关资源
      最近更新 更多