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
library(stringr)
df <- data.frame(X1=1:4,X2=1:4,X5=1:4)
>df
X1 X2 X5
1 1 1 1
2 2 2 2
3 3 3 3
4 4 4 4
current <- as.numeric(str_extract(names(df),"[0-9]"))
missing <-seq(min(current),max(current))
df[paste("X",missing[!missing %in% current],sep="")]<-0
>df[,order(colnames(df))]
X1 X2 X3 X4 X5
1 1 1 0 0 1
2 2 2 0 0 2
3 3 3 0 0 3
4 4 4 0 0 4