Search code examples
rdplyrnse

how to rename a variable using a dynamic name and dplyr?


I want to rename a column inside a function with a name passed as an argument for this function. Basically, I have a function

produce_data_frame <- function(name) {
  return(iris)
}

And I want that this function change the Sepal.length column name with 'name' (with name taking the value of name) I tried different things such as

produce_data_frame <- function(name) {
  name <- enquo(name)
  iris %>%
    rename((!!name) = Sepal.Length) %>%
    return()
}

And when calling

produce_data_frame("newName")

I would like to get back the iris data.frame with the Sepal.Length column named newName. But my understanding of NSE is still very basic, and it doesn't even compile.


Solution

  • You can try

    library(tidyverse)
    
    produce_data_frame <- function(name) {
      iris %>%
        as.tibble() %>% 
        select(!!quo_name(name) := Sepal.Length)
    }
    
    produce_data_frame("new_name")
    #> # A tibble: 150 x 1
    #>    new_name
    #>       <dbl>
    #>  1     5.10
    #>  2     4.90
    #>  3     4.70
    #>  4     4.60
    #>  5     5.00
    #>  6     5.40
    #>  7     4.60
    #>  8     5.00
    #>  9     4.40
    #> 10     4.90
    #> # ... with 140 more rows
    

    Created on 2018-04-04 by the reprex package (v0.2.0).

    Or you can use{{...}}

    produce_data_frame <- function(name) {
      iris %>%
        as_tibble() %>% 
        select({{name}} := Sepal.Length)
    }