Skip to content

Instantly share code, notes, and snippets.

@tjmahr
Created October 11, 2016 20:52
Show Gist options
  • Select an option

  • Save tjmahr/36697532f07d73d93e53eb3372915967 to your computer and use it in GitHub Desktop.

Select an option

Save tjmahr/36697532f07d73d93e53eb3372915967 to your computer and use it in GitHub Desktop.
only_if.R
library("dplyr")
only_if <- function(data, condition, pipeline) {
if (condition) {
pipeline(data)
} else {
data
}
}
iris %>%
arrange(Sepal.Length) %>%
only_if(TRUE, . %>% filter(Species == "versicolor")) %>%
tbl_df
iris %>%
arrange(Sepal.Length) %>%
only_if(FALSE, . %>% filter(Species == "versicolor")) %>%
tbl_df
iris %>%
arrange(Sepal.Length) %>%
only_if(nrow(.) != 1, . %>% mutate(New = "new column")) %>%
tbl_df
iris %>%
arrange(Sepal.Length) %>%
only_if(nrow(.) == 1, . %>% mutate(New = "new column")) %>%
tbl_df
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment