I use dplyr package with a huge dataset. I need to add a new row in each group with a new level of certain factor, but at the same time, I want to repeat other variables from 1st existing row in each group.
str(cstock)
tibble [896 × 37] (S3: tbl_df/tbl/data.frame)
$ ID : chr [1:896] "1" "2" "3" "4" ...
$ pl : Factor w/ 42 levels "D1","D2","D3",..: 1 1 1 1 1 2 2 2 2 2 ...
$ mxdpt : num [1:896] 5.12 5.62 5.25 5.75 6.62 ...
$ lyr : chr [1:896] "NA" "NA" "NA" "NA" ...
$ slyr : Factor w/ 5 levels "lit","min20",..: 1 1 1 1 1 1 1 1 1 1 ...
$ lthkn : num [1:896] 5.12 5.62 5.25 5.75 6.62 ...
$ bulk : num [1:896] 0.0356 0.0518 0.0532 0.0413 0.0444 ...
$ c : num [1:896] 41.1 41.1 41.1 41.1 41.1 ...
$ lstock : num [1:896] 9.13 13.8 11.17 10.32 10.89 ...
$ cstock : num [1:896] 3.75 5.67 4.59 4.24 4.47 ...
$ lcs_cm : num [1:896] 0.731 1.008 0.873 0.737 0.675 ...
I want to add new row with new level "agrnd" to fctr 'slyr', but all the rest variables in new row should be repeated values from 1st row of each group.
I tried this:
cstock %>%
group_by(pl)%>%
group_modify(~ add_row(.x, bulk = .$bulk[1], slyr = "agrnd"))
cstock1$slyr<-as.factor(cstock1$slyr)
This code is working but is there any code that allows me to simply repeat 1st row without specifying them all? In my case 37 variables, I need to repeat most of them. Thanks for the advice!