R: Find missing columns, add to data frame if missing

前端 未结 3 1887
醉话见心
醉话见心 2020-12-16 23:37

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

3条回答
  •  一生所求
    2020-12-17 00:03

    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
    

提交回复
热议问题