Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use dplyr programming syntax to create and evaluate variable names

Tags:

r

rlang

tidyverse

I would like to dynamically input a variable name using dplyr programming syntax, however, as many have described this can be quite confusing.

I've played around with various combinations of quo/enquo !! etc. to no avail. Here is the simplest form of my code

library(tidyverse)

df <- tibble(
  color1 = c("blue", "blue", "blue", "blue", "blue"),
  color2 = c("black", "black", "black", "black", "black"),
  value = 1:5
)

num <- 2

df %>%
  mutate(color3 = !!(paste0("color", num)))


#> # A tibble: 5 x 4
#>   color1 color2 value color3
#>   <chr>  <chr>  <int> <chr> 
#> 1 blue   black      1 color2
#> 2 blue   black      2 color2
#> 3 blue   black      3 color2
#> 4 blue   black      4 color2
#> 5 blue   black      5 color2

Created on 2018-12-19 by the reprex package (v0.2.1)

Instead I would like to evaluate the quoted input.

#> # A tibble: 5 x 4
#>   color1 color2 value color3
#>   <chr>  <chr>  <int> <chr> 
#> 1 blue   black      1 black 
#> 2 blue   black      2 black 
#> 3 blue   black      3 black 
#> 4 blue   black      4 black 
#> 5 blue   black      5 black
like image 529
TDP Avatar asked Dec 19 '18 20:12

TDP


People also ask

How do I use dplyr in R?

Describe what the dplyr package in R is used for. Apply common dplyr functions to manipulate data in R. Employ the 'pipe' operator to link together a sequence of functions. Employ the 'mutate' function to apply other chosen functions to existing columns and create new columns of data.

Which are 5 of the most commonly used dplyr functions?

This article will cover the five verbs of dplyr: select, filter, arrange, mutate, and summarize.

Which of the following functions in dplyr package can be used to choose variables using their names select one?

select() and rename(): For choosing variables and using their names as a base for doing so.

What is dplyr function in R?

dplyr aims to provide a function for each basic verb of data manipulation. These verbs can be organised into three categories based on the component of the dataset that they work with: Rows: filter() chooses rows based on column values.


1 Answers

We can use sym from rlang to convert the string to symbol and then evaluate (!!)

library(dplyr)
df %>%
   mutate(color3 = !!(rlang::sym(paste0("color", num))))
# A tibble: 5 x 4
#  color1 color2 value color3
#  <chr>  <chr>  <int> <chr> 
#1 blue   black      1 black 
#2 blue   black      2 black 
#3 blue   black      3 black 
#4 blue   black      4 black 
#5 blue   black      5 black 
like image 165
akrun Avatar answered Sep 26 '22 13:09

akrun