Fernando Velasco Borea
Fernando Velasco Borea

Reputation: 183

How to avoid the NULL output of str()

I realized that str() returns a NULL to the assigned object (if assigned) and reading a bit I noticed that this is because str() uses the invisible() function under the hood. Is there any argument on str() that disable that so it can actually return the structure of the object?

Upvotes: 2

Views: 1650

Answers (1)

Josh O'Brien
Josh O'Brien

Reputation: 162421

str() is called for its side effect of printing to the console, not for its return value. That said, if you want to capture that text and store it in an object rather than having it printed to the console, you can do so using the function capture.output(). Here's an example:

x <- capture.output(str(mtcars))

x[1:4]
#  [1] "'data.frame':\t32 obs. of  11 variables:"                          
#  [2] " $ mpg : num  21 21 22.8 21.4 18.7 18.1 14.3 24.4 22.8 19.2 ..."  
#  [3] " $ cyl : num  6 6 4 6 8 6 8 4 4 6 ..."                            
#  [4] " $ disp: num  160 160 108 258 360 ..."                            

cat(x[1:4], sep="\n")
# 'data.frame':   32 obs. of  11 variables:
#  $ mpg : num  21 21 22.8 21.4 18.7 18.1 14.3 24.4 22.8 19.2 ...
#  $ cyl : num  6 6 4 6 8 6 8 4 4 6 ...
#  $ disp: num  160 160 108 258 360 ...

Upvotes: 4

Related Questions