r - adding rows to data.frame conditionally -
i have big data.frame
of flowers , fruits in plant 30 years survey. want add zeros (0) in rows represent individuals in specific months plant did not have flowers
or fruits
(because seasonal species).
example:
year month flowers fruits 2004 6 25 2 2004 7 48 4 2005 7 20 1 2005 8 16 1
i want add months not included values of 0 thinking in function recognize missing months , fill them 0.
thanks.
## x data frame gave in question x <- data.frame( year = c(2004, 2004, 2005, 2005), month = c(6, 7, 7, 8), flowers = c(25, 48, 20, 16), fruits = c(2, 4, 1, 1) ) ## y data frame provide missing values, ## can replace 2004 , 2005 whatever desired ## time interval y <- expand.grid(year = 2004:2005, month = 1:12) ## final step fills in missing dates , replaces na's zeros library(tidyr) x <- merge(x, y, = true) %>% replace_na(list(flowers = 0, fruits = 0)) ## if don't want use tidyr, can alternatively x <- merge(x, y, = true) x[is.na(x)] <- 0
it looks this:
head(x, 10) # year month flowers fruits # 1 2004 1 0 0 # 2 2004 2 0 0 # 3 2004 3 0 0 # 4 2004 4 0 0 # 5 2004 5 0 0 # 6 2004 6 25 2 # 7 2004 7 48 4 # 8 2004 8 0 0 # 9 2004 9 0 0 # 10 2004 10 0 0