rdataframedplyrnewrow

Add a new row in each group (Day)


I am trying to make a function with this data and would really appreciate help with this!

    example<- data.frame(Day=c(2,4,8,16,32,44,2,4,8,16,32,44,2,4,8,16,32,44),
          Replicate=c(1,1,1,1,1,1,2,2,2,2,2,2,3,3,3,3,3,3,
                      1,1,1,1,1,1,2,2,2,2,2,2,3,3,3,3,3,3,
                      1,1,1,1,1,1,2,2,2,2,2,2,3,3,3,3,3,3),
          Treament=c("CC","CC","CC","CC","CC","CC","CC","CC","CC","CC","CC","CC","CC","CC","CC","CC","CC","CC",
                     "HP","HP","HP","HP","HP","HP","HP","HP","HP","HP","HP","HP","HP","HP","HP","HP","HP","HP",
                     "LL","LL","LL","LL","LL","LL","LL","LL","LL","LL","LL","LL","LL","LL","LL","LL","LL","LL"),
          AFDM=c(94.669342,94.465752,84.897023,81.435993,86.556221,75.328294,94.262162,88.791240,75.735474,81.232403,
                 67.050593,76.346244,95.076522,88.968823,83.879073,73.958836,70.645724,67.184695,99.763156,92.022673,
                 92.245362,74.513934,50.083136,36.979418,94.872932,86.353037,81.843173,67.795465,46.622106,18.323099,
                 95.089932,93.244212,81.679814,65.352385,18.286525,7.517794,99.559972,86.759404,84.693433,79.196504,
                 67.456961,54.765706,94.074014,87.543693,82.492548,72.333367,51.304676,51.304676,98.340870,86.322153,
                 87.950873,84.693433,63.316485,63.723665))

Example:

I want to insert a new row with an AFDM value (e.g., 0.9823666) that was calculated with another function.

This new row must be on each Day 2 (and call it as Day 0), and I want to preserve the name of each Replica and Treatment of each group.

Thus, this new row must be: Day 0, Replicate=same, Treatment=same, AFDM=0.9823666.

This is so I can later run a regression with the data (from 0 to 44, 3 replicates for each Treatment).

I would prefer a solution on dplyr.

Thanks in advance


Solution

  • We can create a grouping column with cumsum, then expand the dataset with complete and fill the other columns

    library(dplyr)
    library(tidyr)     
    example %>%
        group_by(grp = cumsum(Day == 2)) %>% 
        complete(Day =  c(0, unique(Day)), fill = list(AFDM = 0.9823666)) %>%
        fill(Replicate, Treament, .direction = 'updown')
    # A tibble: 63 x 5
    # Groups:   grp [9]
    #     grp   Day Replicate Treament   AFDM
    #   <int> <dbl>     <dbl> <chr>     <dbl>
    # 1     1     0         1 CC        0.982
    # 2     1     2         1 CC       94.7  
    # 3     1     4         1 CC       94.5  
    # 4     1     8         1 CC       84.9  
    # 5     1    16         1 CC       81.4  
    # 6     1    32         1 CC       86.6  
    # 7     1    44         1 CC       75.3  
    # 8     2     0         2 CC        0.982
    # 9     2     2         2 CC       94.3  
    #10     2     4         2 CC       88.8  
    # … with 53 more rows