I have hockey data, called df
structure(list(event_index = 1:57, coords_x = c(80, 53, 31, -56,
-34, -33, -40, 30, -66, -36, 45, 17, -6, 47, -51, -31, -69, -86,
-70, 80, 65, -76, -71, 81, -57, 80, 75, 77, -71, -40, -83, 62,
77, 76, NA, -61, 69, -45, 68, 31, 58, 61, 80, 34, 80, -85, -37,
-57, 76, 14, 49, -82, -34, -36, -83, -84, -55), coords_y = c(-1,
14, -30, 17, 26, -23, -37, 17, -32, -18, 25, 17, -38, 21, 28,
22, 17, 13, 10, -37, -17, 9, 18, -11, 21, -7, 3, 3, -38, 31,
8, -30, -2, 4, NA, -5, 15, 10, -30, -34, 20, 27, -4, 8, -18,
19, 32, -21, 0, 40, -4, -30, -24, -28, -2, -3, 34), event_rinkside = c("R",
"R", "R", "L", "L", "L", "L", "R", "L", "L", "R", "N", "N", "R",
"L", "L", "L", "L", "L", "R", "R", "L", "L", "R", "L", "R", "R",
"R", "L", "L", "L", "R", "R", "R", NA, "L", "R", "L", "R", "R",
"R", "R", "R", "R", "R", "L", "L", "L", "R", "N", "R", "L", "L",
"L", "L", "L", "L")), class = c("tbl_df", "tbl", "data.frame"
), row.names = c(NA, -57L))
How do I create rows after every single row, leaving me with 57 * 2 (114 rows), but the values in my newly created rows depend on event_rinkside
column.
- If
event_rinkside
equalsR
, then, I want to insert82
intocoords_x
and0
intocoords_y
. - If
event_rinkside
equalsL
, then, I want to insert-82
intocoords_x
and0
intocoords_y
.
I feel like the solution to this SO question is a good starting points, but I don't know how to incorporate my own conditions:
Here is the solution I'm talking about:
library(purrr)
df %>%
group_by(id) %>%
map_dfr(rbind, NA) %>%
mutate(id = rep(df$id, each = 2))