Stefano Borini
Stefano Borini

Reputation: 143795

Obtain a string representation of any R object

I want to be able to obtain a string representation (not a print) of any R object. In python, I would get something like this

>>> class Foo():
...     pass
... 
>>> f = Foo()
>>> print(f)
<__main__.Foo object at 0x10dab0910>
>>> x=str(f)
>>> x
'<__main__.Foo object at 0x10dab0910>'
>>> a = {1, 2,3 }
>>> str(a)
'{1, 2, 3}'
>>> str(str)
"<class 'str'>"
>>> str(foo)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'foo' is not defined
>>> 
KeyboardInterrupt
>>> def foo(): pass
... 
>>> str(foo)
'<function foo at 0x10dab1170>'

In R, I tried the following (quotes from help texts in italic):

I don't want to rely on capture.output because I wish to avoid to pass through stdout to get this information.

Upvotes: 0

Views: 801

Answers (1)

user2554330
user2554330

Reputation: 44867

Use deparse(). For example,

deparse(cars)
#> [1] "structure(list(speed = c(4, 4, 7, 7, 8, 9, 10, 10, 10, 11, 11, "                          
#> [2] "12, 12, 12, 12, 13, 13, 13, 13, 14, 14, 14, 14, 15, 15, 15, 16, "                         
#> [3] "16, 17, 17, 17, 18, 18, 18, 18, 19, 19, 19, 20, 20, 20, 20, 20, "                         
#> [4] "22, 23, 24, 24, 24, 24, 25), dist = c(2, 10, 4, 22, 16, 10, 18, "                         
#> [5] "26, 34, 17, 28, 14, 20, 24, 28, 26, 34, 34, 46, 26, 36, 60, 80, "                         
#> [6] "20, 26, 54, 32, 40, 32, 40, 50, 42, 56, 76, 84, 36, 46, 68, 32, "                         
#> [7] "48, 52, 56, 64, 66, 54, 70, 92, 93, 120, 85)), class = \"data.frame\", row.names = c(NA, "
#> [8] "-50L))"

Created on 2020-07-24 by the reprex package (v0.3.0)

For most objects, you can parse and evaluate the output and get an object like the original.

Upvotes: 5

Related Questions