R对象识别 [英] R object identification
问题描述
我经常得到一个生成输出的函数,但我不了解其输出数据类型.我期待一个列表,它最终成为一个列表列表或一个数据框或其他东西.首次使用函数时确定输出数据类型的好方法或工作流程是什么?
I am often ending up with a function producing output for which I don't understand the output data type. I'm expecting a list and it ends up being a list of lists or a data frame or something else. What's a good method or workflow for figuring out the output data type when first using a function?
推荐答案
我通常从以下组合开始:
I usually start out with some combination of:
typeof(obj)
class(obj)
sapply(obj, class)
sapply(obj, attributes)
attributes(obj)
names(obj)
根据所披露的内容酌情决定.例如,尝试:
as appropriate based on what's revealed. For example, try with:
obj <- data.frame(a=1:26, b=letters)
obj <- list(a=1:26, b=letters, c=list(d=1:26, e=letters))
data(cars)
obj <- lm(dist ~ speed, data=cars)
..等
如果obj
是S3或S4对象,你也可以试试methods
或showMethods
,showClass
,等等.Patrick Burns 的 R Inferno 对此有一个很好的部分(第 7 秒).
If obj
is an S3 or S4 object, you can also try methods
or showMethods
, showClass
, etc. Patrick Burns' R Inferno has a pretty good section on this (sec #7).
编辑:Dirk 和 Hadley 在他们的回答中提到了 str(obj)
.对于快速甚至详细地查看对象,它确实比上述任何一种都要好得多.
EDIT: Dirk and Hadley mention str(obj)
in their answers. It really is much better than any of the above for a quick and even detailed peek into an object.
这篇关于R对象识别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!