I\'d like to write some code that would take a given data frame, check to see if any columns are missing, and if so, add the missing columns filled with 0 or NA. Here\'s wha
Here's a straightforward approach
df <- data.frame(a=1:4, e=4:1)
nms <- c("a", "b", "d", "e") # Vector of columns you want in this data.frame
Missing <- setdiff(nms, names(df)) # Find names of missing columns
df[Missing] <- 0 # Add them, filled with '0's
df <- df[nms] # Put columns in desired order
# a b d e
# 1 1 0 0 4
# 2 2 0 0 3
# 3 3 0 0 2
# 4 4 0 0 1