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 what I’ve got:
> df
x1 x2 x4
1 0 1 3
2 3 1 3
3 1 2 1
> nameslist <- c("x1","x2","x3","x4")
> miss.names <- !nameslist %in% colnames(df)
> holder <- rbind(nameslist,miss.names)
> miss.cols <- subset(holder[1,], holder[2,] == "TRUE")
Beyond this point, I can’t figure out how to add in the missing column (“x3”) without hardcoding it. Ideally, I’d want the new, complete data frame to have columns in the same order as nameslist as well.
Any ideas? My current code can be ignored, no problem.
Here’s a straightforward approach