rdataframedplyrrowtibble

Add row in each group using dplyr and add_row()


If I add a new row to the iris dataset with:

iris <- as_tibble(iris)

> iris %>% 
    add_row(.before=0)

# A tibble: 151 × 5
    Sepal.Length Sepal.Width Petal.Length Petal.Width Species
          <dbl>       <dbl>        <dbl>       <dbl>   <chr>
1            NA          NA           NA          NA    <NA> <--- Good!
2           5.1         3.5          1.4         0.2  setosa
3           4.9         3.0          1.4         0.2  setosa

It works. So, why can't I add a new row on top of each "subset" with:

iris %>% 
 group_by(Species) %>% 
 add_row(.before=0)

Error: is.data.frame(df) is not TRUE

Solution

  • A more recent version would be using group_modify() instead of do().

    iris %>%
      as_tibble() %>%
      group_by(Species) %>% 
      group_modify(~ add_row(.x,.before=0))
    #> # A tibble: 153 x 5
    #> # Groups:   Species [3]
    #>    Species Sepal.Length Sepal.Width Petal.Length Petal.Width
    #>    <fct>          <dbl>       <dbl>        <dbl>       <dbl>
    #>  1 setosa          NA          NA           NA          NA  
    #>  2 setosa           5.1         3.5          1.4         0.2
    #>  3 setosa           4.9         3            1.4         0.2