lukstei
lukstei

Reputation: 886

R list to string representation

I want to get a string representation of a list, which can be used to recreate a list with the same value.

What I'm searching for is a function like the Python repr() function.

model = list(name='ugarch', spec=list(garchOrder = c(1, 1)))

str = str_repr(model)

# str should be equal to "list(name='ugarch', spec=list(garchOrder = c(1, 1)))"

Is there a way to do this in R?

Upvotes: 1

Views: 630

Answers (1)

Empiromancer
Empiromancer

Reputation: 3854

The dput function almost does what you want: it attempts to deparse an object into an ASCII text representation. However, it's not very suitable for programming: the string representation is written to stdout or a file (default is to write to the console), and the actual output is just an invisible copy of the input:

dput(list(x = 1))
## structure(list(x = 1), .Names = "x")
y <- dput(list(x = 1))
## structure(list(x = 1), .Names = "x")
y
## $x
## [1] 1

class(y)
## [1] "list"

However, you can use dput and capture.output to write a function that has the behavior you want:

repr <- function(x) {
    y <- capture.output(dput(x))
    paste(y, collapse = '')
}

z <- repr(list(x = 1))
z
## [1] "structure(list(x = 1), .Names = \"x\")"
class(z)
## [1] "character"

Upvotes: 3

Related Questions