r - Select columns of dataframe filling with NA's in selected column doesn't exist -


take example data frame

temp <- data.frame('a' = 1:3, 'b' = 4:6, 'd' = 7:9) 

i want subset data frame using vector of column names, if vector contains columns don't exist in data frame want them still returned na.

so if vector

colvec <- c('a', 'b', 'c') 

i want run along lines of

subset(temp, select = colvec) 

to get

a b c 1 4 na 2 5 na 3 6 na 

you can in 2 steps -- limiting requested columns in data frame , adding requested columns not in data frame. can use intersect , setdiff these 2 sets of column names:

temp2 <- temp[intersect(colvec, names(temp))] temp2[setdiff(colvec, names(temp))] <- na temp2 #   b  c # 1 1 4 na # 2 2 5 na # 3 3 6 na 

Comments

Popular posts from this blog

javascript - how to protect a flash video from refresh? -

android - Associate same looper with different threads -

visual studio 2010 - Connect to informix database windows form application -