R包CRAN审核问题:如何用inherits()/is()替换class()判断且保留原意?
问题描述
我正在更新一个R包,但已四年未使用R语言,很多内容已遗忘。将包上传至CRAN后,收到了若干警告与提示,我已解决警告,但仍有一行代码存在问题。该行代码如下:
if (class(file) == "data.frame" || class(file2) == "data.frame")
CRAN给出的问题提示如下:
Found if() conditions comparing class() to string: File 'DFA/R/DFA.R': if (class(file) == "data.frame" || class(file2) == "data.frame") ... File 'DFA/R/DFA.R': if (class(file) == "data.frame" || class(file2) == "data.frame") ... File 'DFA/R/DFA.R': if (class(file) == "data.frame" || class(file2) == "data.frame") ... File 'DFA/R/DFA.R': if (class(file) == "data.frame" || class(file2) == "data.frame" || class(file3) == "data.frame" || class(file4) == "data.frame") ... Use inherits() (or maybe is()) instead.
请问如何修改代码,使用inherits()或is()且不丢失原有逻辑?
解决方案
使用is.data.frame()函数
is.data.frame()是R中专门用于判断对象是否为data.frame(或继承自data.frame的类)的函数,比直接比较class()返回值更可靠——当对象拥有多个类属性时,class(x) == "data.frame"可能返回FALSE,但is.data.frame(x)仍能正确识别。替换后完全保留原逻辑:只要任一对象是data.frame,条件就成立。
替换后的双对象判断代码:
if (is.data.frame(file) || is.data.frame(file2))
多对象判断的情况:
if (is.data.frame(file) || is.data.frame(file2) || is.data.frame(file3) || is.data.frame(file4))
使用inherits()函数
inherits()是通用的类继承判断函数,可检查对象是否继承自指定类,同样能覆盖原逻辑,且适用于更广泛的类判断场景。
替换后的双对象判断代码:
if (inherits(file, "data.frame") || inherits(file2, "data.frame"))
多对象判断的情况:
if (inherits(file, "data.frame") || inherits(file2, "data.frame") || inherits(file3, "data.frame") || inherits(file4, "data.frame"))
两者差异
is.data.frame()语义更明确,专门针对data.frame类型的判断,可读性更强。inherits()更灵活,可用于检查任意类的继承关系,若你的包未来需要支持自定义的data.frame子类,两者都能正常工作,但is.data.frame()更直观。
内容的提问来源于stack exchange,提问作者Victor Barreto
相关产品推荐
相关产品推荐

