Escape slips in a tee

If I want to make recoding explicit, I can use a pronoun .data like this

 library(dplyr) cyl <- 3 transmute(as_tibble(mtcars), cyl_plus_one = .data$cyl + 1) #> # A tibble: 32 x 1 #> cyl_plus_one #> <dbl> #> 1 7 #> 2 7 #> 3 5 #> 4 7 #> 5 9 #> 6 7 #> 7 9 #> 8 5 #> 9 5 #> 10 7 #> # ... with 22 more rows 

However, what about the opposite, i.e. if i want to avoid an overturn? In the example below, I would like to add a new column that contains the value b (supplied through a function call, not b in the data) plus 1, which obviously does not work as it was indicated now (due to overscoping).

 library(dplyr) add_one <- function(data, b) { data %>% mutate(a = b + 1) } data <- data_frame( b = 999 ) add_one(data, 3) #> # A tibble: 1 x 2 #> ba #> <dbl> <dbl> #> 1 999 1000 

I also tried to create a new value outside the mutate() call, but then I still need to rely on new_val not the data.

 library(dplyr) add_one <- function(data, b) { new_val <- b + 1 data %>% mutate(a = new_val) } 
+5
source share
1 answer

Just unquote with !! to search for a variable with this name above the data frame area:

 library(tidyverse) add_one <- function(data, b) { data %>% mutate(a = !!b + 1) } data <- data_frame(b = 999) add_one(data, 3) #> # A tibble: 1 x 2 #> ba #> <dbl> <dbl> #> 1 999 4.00 
+6
source

Source: https://habr.com/ru/post/1274668/


All Articles