Skip to content

Instantly share code, notes, and snippets.

@alexpghayes
Last active February 3, 2021 22:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alexpghayes/6d087461743e1ffde9de229159bdd39f to your computer and use it in GitHub Desktop.
Save alexpghayes/6d087461743e1ffde9de229159bdd39f to your computer and use it in GitHub Desktop.
``` r
library(tidyverse)
library(lubridate)
#>
#> Attaching package: 'lubridate'
#> The following objects are masked from 'package:base':
#>
#> date, intersect, setdiff, union
# As an example, let's say I have a dataframe of birthdays:
birthdays <- tibble(name = c("Anna", "Bobby", "Camille", "Deanna", "Ernie", "Francine"),
birthday = c("2020-05-02", "2020-03-25", "2020-06-08", "2020-01-31", "2020-08-14", "2020-07-03") %>% as_date())
# And I have another dataframe with the data ranges for various astrological "signs":
sign <- tibble(name = c("Aries", "Taurus", "Gemini", "Cancer", "Leo"),
start_date = c("2020-03-21", "2020-04-20", "2020-05-21", "2020-06-21", "2020-07-23") %>% as_date(),
end_date = c("2020-04-19", "2020-05-20", "2020-06-20", "2020-07-22", "2020-08-22") %>% as_date()) %>%
mutate(interval = interval(start_date, end_date))
# For each row of `birthdays`, I can manually calculate each sign:
birthdays %>%
mutate(is_aries = birthday %within% sign$interval[1],
is_taurus = birthday %within% sign$interval[2])
#> # A tibble: 6 x 4
#> name birthday is_aries is_taurus
#> <chr> <date> <lgl> <lgl>
#> 1 Anna 2020-05-02 FALSE TRUE
#> 2 Bobby 2020-03-25 TRUE FALSE
#> 3 Camille 2020-06-08 FALSE FALSE
#> 4 Deanna 2020-01-31 FALSE FALSE
#> 5 Ernie 2020-08-14 FALSE FALSE
#> 6 Francine 2020-07-03 FALSE FALSE
get_sign_name <- function(date) {
is_sign <- date %within% sign$interval
if (!any(is_sign))
return("No corresponding sign")
sign$name[which(is_sign)]
}
birthdays %>%
mutate(
sign = map_chr(birthday, get_sign_name)
)
#> # A tibble: 6 x 3
#> name birthday sign
#> <chr> <date> <chr>
#> 1 Anna 2020-05-02 Taurus
#> 2 Bobby 2020-03-25 Aries
#> 3 Camille 2020-06-08 Gemini
#> 4 Deanna 2020-01-31 No corresponding sign
#> 5 Ernie 2020-08-14 Leo
#> 6 Francine 2020-07-03 Cancer
```
<sup>Created on 2021-02-03 by the [reprex package](https://reprex.tidyverse.org) (v1.0.0.9000)</sup>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment