Home > Software design >  Difference between inherits(x,"data.frame") and "class" %in% class("data.fr
Difference between inherits(x,"data.frame") and "class" %in% class("data.fr

Time:06-16

Are these any different from each other? Assume x is defined:

inherits(x,"data.frame")

"data.frame" %in% class(x)

Also, it need not be "data.frame". It can be something else like "workflow". I just want to know as these seem to do the same thing (i.e. check if x is a data frame), but I feel like they might be different.

CodePudding user response:

The main difference is in vectorized class checking, for example if you want to check whether an object belongs to one of a number of different classes. Then inherits will return a length-one logical vector, whereas %in% returns multiple results (one for each test class)

df  <- data.frame(a = 1:3)

inherits(df, c("data.frame", "foo"))
#> [1] TRUE

c("data.frame", "foo") %in% class(df)
#> [1]  TRUE FALSE

This could be relevant when using a logical test of class type. For example, suppose I want to check that df is either a data frame or of class foo. I can safely put inherits inside an if statement:

if(inherits(df, c("data.frame", "foo"))) {
  cat("Object df is either a data frame or a foo")
}
#> Object df is either a data frame or a foo

But I will get an error if I do the same thing with %in%

if(c("data.frame", "foo") %in% class(df)) {
  cat("Object df is either a data frame or a foo")
}
#> Error in if (c("data.frame", "foo") %in% class(df)) {
#> : the condition has length > 1

If you only want to check for a single class, the two are essentially equivalent, or in the case of tests for multiple classes, wrapping the %in% with any will achieve the same effect.

Created on 2022-06-15 by the reprex package (v2.0.1)

  •  Tags:  
  • r
  • Related