I have a dataframe of factors and corresponding values like this:
df <- data.frame(week = factor(c(1,2,49,50)), occurrences = c(1,4,2,3))
week occurrences
1 1 1
2 2 4
3 49 2
4 50 3
I want to add factors for all the "missing" weeks in (1-53) with the corresponding occurrences value of 0. What is the best way to do this? I have to do this to several data frames that may not be "missing" the same factors so I would like to generalize it in a function.
You can use rbind()
to append the necessary lines to your df
, in this example, I first create the df to be added before appending it for clarity. setdiff()
will return the numbers currently not present in your week column:
df_to_app = data.frame(week = factor(setdiff(1:52, df$week)), occurrences = 0)
df = rbind(df, df_to_app)
I hope that helps!