r - How to search for a specific column name in data -


so bit strange, pretty new r , facing weird problem. have data frame, , there column called sndate combined value of 2 different columns.

i want check if data frame has column named sn, if doesn't split sndate fill sn column.

here code

if(!('sn' %in% colnames(data))){      #do spliting here } 

funny thing is, keeps saying it's there, , stuff in never gets triggered. , when this:

print(data$sn) 

it print value of data$sndate. r have sort of lazy name filling or something? strange me.

thank help

when

print(data$sn) 

it works because $ using partial name matching. example, try

mtcars$m 

there no column named m, $ partially matches mpg. unfortunately, not used in %in%, need use complete exact column name in

if(!('sndate' %in% colnames(data))){      #do spliting here } 

you insead use along lines of pmatch()

names(mtcars)[2] <- "sndate" names(mtcars)[pmatch("sn", names(mtcars))] # [1] "sndate" 

so if() statement might go -

nm <- colnames(data) if(!nm[pmatch("sn", nm)] %in% nm) {     ... } 

or even

if(is.na(pmatch("sn", names(data))) 

might better


Comments