Preferred method of checking object's class in

2019-06-14 21:12发布

What is the preferred method of checking an object's class in R?

(1)

is.data.frame(df)

(2)

class(df) == 'data.frame'

(3)

'data.frame' %in% class(df)

2条回答
贼婆χ
2楼-- · 2019-06-14 21:47

I would say

inherits(df,"data.frame")

or

is(df,"data.frame")

among other things, #2 in your list can fail because (as you suggest in #3) class(df) can have length > 1. (is.data.frame is nice, but not all classes have is. methods: see methods("is"))

查看更多
男人必须洒脱
3楼-- · 2019-06-14 22:09

For me it'd be:

is.data.frame(df)

Is a clearer option to use in conditions. Also, is the 'less code' option of the three, if that is important for you.

查看更多
登录 后发表回答