r - Find which colnames are undefined and create them -


so have data frame

povprecja.predmeti 

enter image description here

and in data.frame have columns named:

"krediti_razporejanje_n_2"
"krediti_razporejanje_n_3"
"krediti_razporejanje_n_4" "krediti_razporejanje_n_5"

i generate/define column name krediti_razporejanje_n_1, i have 5 column names defined. because of different data frames have dinamic code, means

i find (from krediti_razporejanje_n_1 krediti_razporejanje_n_5) colname undefined , define column name , fill values 0. if example mising column

krediti_razporejanje_n_1 assign <- 0 

i know hand like:

povprecja.predmeti$krediti_razporejanje_n_1 <- rep(0,nrow(povprecja.predmeti)) 

but need function, if data there 2 colnames defined, find 1-5 undefined , define them.

i can find 1 missing code

which(paste0("krediti_razporejanje_n_", 1:5) %in% colnames(povprecja.predmeti)==false) 

but have dinamic function.

miscol <- function(x){ # x = data.frame missing <- paste0("krediti_razporejanje_n_",1:5)[paste0("krediti_razporejanje_n_", 1:5) %in% colnames(x) == false] res <- list() for(i in missing){ res[[i]] <- rep(0,nrow(x)) } new <- data.frame(x,res) return(new[,sort(colnames(new))]) } 

as new user , cannot comment, guess have answer. should want do.

there better way instead of using empty list write new columns though. take column names missing, give them zeros , write new data-frame.


Comments

Popular posts from this blog

Hatching array of circles in AutoCAD using c# -

ios - UITEXTFIELD InputView Uipicker not working in swift -

Python Pig Latin Translator -