r - Add columns in vector but not in df -


i trying following , wondering if there easier way use dplyr achieve (i'm sure there is):

i want compare columns of dataframe vector of names, , if df not contain column corresponding 1 of names in name vector, add column df , populate values nas.

e.g., in mwe below:

df <- data.frame(cbind(c(1:6),c(11:16),c(10:15))) colnames(df) <- c("a","b","c") names <- c("a","b","c","d","e") 

how use dplyr create 2 columns d , e (which in names, not in df) , populate nas?

no need in dplyr, it's basic operation in base r. (btw, try avoiding overriding built in functions such names in future. reason names still works because r looks in base package namespace file instead in global environment, still bad practice.)

df[setdiff(names, names(df))] <- na df #    b  c  d  e # 1 1 11 10 na na # 2 2 12 11 na na # 3 3 13 12 na na # 4 4 14 13 na na # 5 5 15 14 na na # 6 6 16 15 na na 

Comments

Popular posts from this blog

html - Outlook 2010 Anchor (url/address/link) -

javascript - Why does running this loop 9 times take 100x longer than running it 8 times? -

Getting gateway time-out Rails app with Nginx + Puma running on Digital Ocean -