Here is my dataframe:
structure(list(Dispensary = c("A", "A", "A", "A", "A", "A", "A",
"A", "A", "B", "B", "B", "B", "B", "B", "B", "B", "B", "C", "C",
"C", "C", "C", "C", "C", "C", "C"), cohort = c(1L, 2L, 3L, 4L,
5L, 6L, 7L, 8L, 9L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 1L, 2L,
3L, 4L, 5L, 6L, 7L, 8L, 9L), t0 = c(100, 100, 100, 100, 100,
100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100,
100, 100, 100, 100, 100, 100, 100, 100, 100), t1 = c(46.1, 41.7,
37.5, 36.2, 35.9, 34.4, 39.8, 38.3, 0, 34.6, 37.4, 31.4, 29.5,
25.5, 33.2, 30.6, 30.8, 0, 28.6, 30.2, 28.1, 28.8, 30.7, 29.2,
33.5, 30.3, 0), t2 = c(41.4, 34.6, 38.6, 27.9, 30, 32.8, 35.2,
0, 0, 35.2, 31.4, 23.9, 24.2, 23.1, 30.1, 24, 0, 0, 26.9, 24.8,
21, 25.3, 25.8, 25.9, 23.3, 0, 0), t3 = c(29.6, 32.3, 31.7, 25.8,
29.5, 23.8, 0, 0, 0, 25.2, 28.9, 23, 23.8, 20.5, 22.6, 0, 0,
0, 20.7, 24, 21.5, 24.9, 23, 23.7, 0, 0, 0), t4 = c(30.9, 28,
30.4, 24.9, 29.5, 0, 0, 0, 0, 23.1, 23.1, 20.7, 21.8, 19.2, 0,
0, 0, 0, 21, 20.8, 21.3, 23.7, 20.5, 0, 0, 0, 0), t5 = c(30.3,
25.6, 23.5, 24.9, 0, 0, 0, 0, 0, 19.4, 22.1, 20, 19.5, 0, 0,
0, 0, 0, 17.2, 18.5, 20.4, 14.7, 0, 0, 0, 0, 0), t6 = c(30.9,
24, 23.2, 0, 0, 0, 0, 0, 0, 19.6, 20.3, 17.2, 0, 0, 0, 0, 0,
0, 20.3, 17.7, 18.2, 0, 0, 0, 0, 0, 0), t7 = c(27.6, 18.5, 0,
0, 0, 0, 0, 0, 0, 18, 16.1, 0, 0, 0, 0, 0, 0, 0, 14.2, 14.8,
0, 0, 0, 0, 0, 0, 0), t8 = c(17.8, 0, 0, 0, 0, 0, 0, 0, 0, 17.2,
0, 0, 0, 0, 0, 0, 0, 0, 11.4, 0, 0, 0, 0, 0, 0, 0, 0)), row.names = c(NA,
-27L), class = c("tbl_df", "tbl", "data.frame"))
I'm trying to insert a blank row after every 9th row, in between where cohort == 9
and cohort == 1
The dataframe is long and I'm hoping to not have to do it one a time
Here is a link to a similar question, but I'm looking for an R method, not a VBA method
CodePudding user response:
Here is an option:
library(tidyverse)
df |>
group_split(Dispensary) |>
map_dfr(~add_row(.x))
#> # A tibble: 30 x 11
#> Dispensary cohort t0 t1 t2 t3 t4 t5 t6 t7 t8
#> <chr> <int> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
#> 1 A 1 100 46.1 41.4 29.6 30.9 30.3 30.9 27.6 17.8
#> 2 A 2 100 41.7 34.6 32.3 28 25.6 24 18.5 0
#> 3 A 3 100 37.5 38.6 31.7 30.4 23.5 23.2 0 0
#> 4 A 4 100 36.2 27.9 25.8 24.9 24.9 0 0 0
#> 5 A 5 100 35.9 30 29.5 29.5 0 0 0 0
#> 6 A 6 100 34.4 32.8 23.8 0 0 0 0 0
#> 7 A 7 100 39.8 35.2 0 0 0 0 0 0
#> 8 A 8 100 38.3 0 0 0 0 0 0 0
#> 9 A 9 100 0 0 0 0 0 0 0 0
#> 10 <NA> NA NA NA NA NA NA NA NA NA NA
#> # ... with 20 more rows
CodePudding user response:
Assuming you are trying to add a row after every Dispensary
you could do:
library(dplyr)
library(purrr)
df %>%
group_split(Dispensary) %>%
map_dfr(add_row)
If you do actually need to insert after every 9th row you can do:
df %>%
group_split(group = rep(1:(nrow(.) / 9), each = 9)) %>%
map_dfr(add_row) %>%
select(-group)