R object identification

RObject

R Problem Overview


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?

R Solutions


Solution 1 - R

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)

..etc.

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).

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.

Solution 2 - R

str(x)

It's all you need to remember for 99% of cases.

Solution 3 - R

If I get 'someObject', say via

someObject <- myMagicFunction(...)

then I usually proceed by

class(someObject)
str(someObject)

which can be followed by head(), summary(), print(), ... depending on the class you have.

Solution 4 - R

attributes(someObject) 

Can also be useful

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJD LongView Question on Stackoverflow
Solution 1 - RarsView Answer on Stackoverflow
Solution 2 - RhadleyView Answer on Stackoverflow
Solution 3 - RDirk EddelbuettelView Answer on Stackoverflow
Solution 4 - RJosh ReichView Answer on Stackoverflow