user4110499
user4110499

Reputation:

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

I have two data frames like this:

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 can I check if they have the same column names with an ifelse or if loop statement with a warning or stop function? Or is there an other..? I would prefer the the former.

Upvotes: 9

Views: 11146

Answers (1)

LyzandeR
LyzandeR

Reputation: 37889

I think what you need is something like the following using 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"

Upvotes: 9

Related Questions