Last active
October 20, 2022 21:00
-
-
Save grayskripko/b4249018465e0db307ad56bf68c3fe3d to your computer and use it in GitHub Desktop.
R pivot longer-wider example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
pivot_longer( | |
cols=-c(date, match_id), | |
names_to=c("side", ".value"), | |
names_sep='(?<=^[ha])_') | |
pivot_wider( | |
id_cols=c(date, h_team, a_team), | |
names_from=side, | |
names_glue = "{side}_{.value}", | |
values_from=-c(date, h_team, a_team, team, side)) | |
print(exmpl) %>% | |
+ pivot_wider( | |
+ c(date, team, is_home), | |
+ names_from=name, values_from=matches('_[1m]'), | |
+ names_glue='{name}{.value}') | |
# A tibble: 1,947,728 x 7 | |
date team is_home name `_1` `_ma5` `_ma20` | |
<date> <chr> <lgl> <chr> <dbl> <dbl> <dbl> | |
1 2012-10-30 CLE TRUE score NA NA NA | |
2 2012-10-30 CLE TRUE margin NA NA NA | |
... | |
date team is_home score_1 margin_1 total_score_1 fgm_1 fga_1 pct_fg_1 fg3m_1 | |
<date> <chr> <lgl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> | |
1 2012-10-30 CLE TRUE NA NA NA NA NA NA NA | |
2 2012-10-30 WAS FALSE NA NA NA NA NA NA NA |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment