Reputation: 143795
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):
as.character()
: If I pass a vector I expect a string containing the vector, not a vector of strings, so as.character
is not what I want.
str()
"does not return anything", it just prints it:
a <- str(str)
# function (object, ...)
a
# NULL
I don't want to rely on capture.output
because I wish to avoid to pass through stdout to get this information.
toString()
"A character vector of length 1 is returned", i.e. not what I need, e.g. when applied on a data.frame
:
toString(cars)
# [1] "c(4, 4, 7, 7, 8, 9, 10, 10, 10, 11, 11, 12, 12, 12, 12
The functionality of print()
doesn't meet my needs for the same reason as str()
(see above). In addition, if the entity is something that can be rendered, it will trigger a rendering instead of a string representation.
cat()
"Currently only atomic vectors and names are handled". Thus, cat
will error for a data.frame
:
cat(cars)
# Error in cat(cars) : argument 1 (type 'list') cannot be handled by 'cat'
Upvotes: 0
Views: 801
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