Skip to content

Instantly share code, notes, and snippets.

@batpigandme
Created November 15, 2018 22:59
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save batpigandme/e9103126d235bbf6d73da989b3c71142 to your computer and use it in GitHub Desktop.
Save batpigandme/e9103126d235bbf6d73da989b3c71142 to your computer and use it in GitHub Desktop.
Playing w/ data mask example from tidy eval cheatsheet

Data mask stuff

Adapted from Tidy evaluation with rlang cheat sheet

library(rlang)

Sometimes a variable name has a value in the global environment and is the name of a variable inside of a data frame (try to avoid having this happen, it’s confusing).

# variables in global env
a <- "life"
b <- "line"

stringr::str_c(a, b)
## [1] "lifeline"
# one row data frame
mydat <- tibble::tibble(a = "coast", b = "guard")

mydat
## # A tibble: 1 x 2
##   a     b    
##   <chr> <chr>
## 1 coast guard
# the experssion we'll evaluate, quoted to use later as a quosure
p <- quo(stringr::str_c(.data$a,!!b))

# using `eval_tidy()`
eval_tidy(p, data = mydat)
## [1] "coastline"
# the experssion we'll evaluate, quoted to use later as a quosure
q <- quo(stringr::str_c(!!a, .data$b))

# using `eval_tidy()`
eval_tidy(q, data = mydat)
## [1] "lifeguard"
---
title: "Data mask stuff"
output: github_document
---
```{r include=FALSE, message=FALSE, warning=FALSE}
knitr::opts_chunk$set(
message = FALSE, warning = FALSE, echo = TRUE, fig.retina = 2, collapse = TRUE
)
```
__Adapted from [Tidy evaluation with rlang cheat sheet](https://github.com/rstudio/cheatsheets/raw/master/tidyeval.pdf)__
```{r}
library(rlang)
```
Sometimes a variable name has a value in the global environment _and_ is the name of a variable inside of a data frame (try to avoid having this happen, it's confusing).
```{r}
# variables in global env
a <- "life"
b <- "line"
stringr::str_c(a, b)
```
```{r}
# one row data frame
mydat <- tibble::tibble(a = "coast", b = "guard")
mydat
```
```{r}
# the experssion we'll evaluate, quoted to use later as a quosure
p <- quo(stringr::str_c(.data$a,!!b))
# using `eval_tidy()`
eval_tidy(p, data = mydat)
```
```{r}
# the experssion we'll evaluate, quoted to use later as a quosure
q <- quo(stringr::str_c(!!a, .data$b))
# using `eval_tidy()`
eval_tidy(q, data = mydat)
```
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment