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 ?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With