How to check if two data frames have the same column names?

I have two data frames:

quest1 <- c(5,5,5)
quest2 <- c(5,5,5)
quest3<- c("a","b","c")
quest4 <- c(7,7,7)
quest5 <- c(8,8,8)


myquest1 <- data.frame(quest1,quest2,quest3)

myquest2 <- data.frame(quest4,quest5)

How to check if they have the same column names with the ifelse or if statement with the warning or stop function ? Or is there another ..? I would prefer the first one.

+4
source share
1 answer

I think you need something like the following with a function.

Using your example:

quest1 <- c(5,5,5)
quest2 <- c(5,5,5)
quest3<- c("a","b","c")
quest4 <- c(7,7,7)
quest5 <- c(8,8,8)

myquest1 <- data.frame(quest1,quest2,quest3)
myquest2 <- data.frame(quest4,quest5)
myquest3 <- data.frame(quest1,quest2,quest3)


my_func <- function(x,y) {
    for (i in names(x)) {
      if (!(i %in% names(y))) {
          print('Warning: Names are not the same')
          break
      }  
      else if(i==tail(names(y),n=1)) {
          print('Names are identical')
      }
    }
}


> my_func(myquest1,myquest2)
[1] "Warning: Names are not the same"
> my_func(myquest1,myquest3)
[1] "Names are identical"
+2
source

All Articles