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?
4 Answers
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.
-
1i don't think I made it that far through R Inferno. Thanks for sending me back there.– JD LongJul 24, 2009 at 20:50
-
3In case you haven't seen it already, "S4 objects in 15 pages or less" [ stat.auckland.ac.nz/S-Workshop/Gentleman/S4Objects.pdf ] is another good read (with more details).– arsJul 24, 2009 at 23:02
-
I had not see that. Thanks for the link. That was worth the price of admission. :)– JD LongJul 26, 2009 at 1:16
-
I've created a little utility function that encodes this suggestion. See tellMeAboutThis.r– eludomOct 11, 2014 at 21:06
str(x)
It's all you need to remember for 99% of cases.
-
2
-
7str(UCTURE) hard to remember, 'cause I keep thinking "string" but oh, so useful. Will just have to say strUCTURE ten times.– DmitriAug 15, 2015 at 1:01
-
if I have
str(x)
returningNamed num [1:10] 1.555 8.424 .... -attr(*,"names")= chr [1:10] "x1" "x2" ...
what does that mean? Is this an atomic vector with names?– JamesDec 30, 2021 at 20:45 -
more generally, how do I know if an object is a matrix, dataframe, etc?
str()
does not seem to expose this.– JamesDec 30, 2021 at 20:52
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.
-
Just tried str(obj). Way more than I expected from a string representation; very neat! Thanks.– arsJul 26, 2009 at 21:36