Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

find whether a column exists in R data frame and if not then create it

Tags:

r

I have following dataframe in R

 no     qc6    qc5    qc3     itv6   itv5    itv3
123      12    12     14      8      9       9

Now, I want to check whether following columns exist in a dataframe or not and if not then create a new column with 0 value in it.

 qc1,qc2,itv1,itv2

I can do it with if loop in R

 if(!"qc1" %in% colnames(df))
 {
   df$qc1 <- 0
 }

But, then I will have to write loops for every variable to create. Is there any faster way of doing it ?

like image 723
Neil Avatar asked Dec 13 '22 18:12

Neil


1 Answers

If you have a vector of names that you know should be in it, the following will check if they already have a column. If not, they'll create one with value 0.

x <- c( "qc1","qc2","itv1","itv2", "no" )
d <- data.frame( no = 123,    qc6 = 12,    qc5 = 12,    qc3 = 14,     itv6 = 8,   itv5 = 9,    itv3 = 9)

d[x[!(x %in% colnames(d))]] = 0
d

This gives the output:

 no     qc6    qc5    qc3     itv6   itv5    itv3    qc1    qc2    itv1    itv2
123      12    12     14      8      9       9       0      0      0       0
like image 134
AodhanOL Avatar answered Dec 17 '22 22:12

AodhanOL