João Duarte
João Duarte

Reputation: 69

print a parameter's value, including its type

I have a variable, lets call it artichoke, that can be either a sequence or a vector, for example

artichoke <- seq(-5,5)

or

artichoke <- c(-5,5)

I want to print the value and type of this variable so that I would get:

seq(-5,5)

in the first case and

c(-5,5)

in the second.

How can I do this?

Upvotes: 1

Views: 437

Answers (2)

Ben Bolker
Ben Bolker

Reputation: 226427

There is a function called dput() in R that turns out to be cleverer than I gave it credit for ...

artichoke <- c(-5,5)
dput(artichoke, file=textConnection("art1","w"))
artichoke <- seq(-5,5)
dput(artichoke, file=textConnection("art2","w"))

Results:

art1
## [1] "c(-5, 5)"
art2
## [1] "-5:5"

R chooses to use the : operator rather than seq() . You could use something like

sub("(-?[0-9]+):(-?[0-9]+)","seq(\\1,\\2)",art2)

to convert the result from -5:5 to seq(-5,5) if you wanted.

If the sequence is more complex dput() is not as clever/doesn't recognize it as a sequence:

artichoke <- seq(-5,10,by=2)
dput(artichoke)
## c(-5, -3, -1, 1, 3, 5, 7, 9)

If you wanted to recognize this or other more complex cases you'd probably have to write your own rules ...

Upvotes: 2

akrun
akrun

Reputation: 887291

If we want to delay the execution, can be wrapped in quote

artichoke <-  quote(seq(-5, 5))

and then eval to return the evaluated output

eval(artichoke)
#[1] -5 -4 -3 -2 -1  0  1  2  3  4  5
artichoke
#seq(-5, 5)

Another option is to create a function, extract the arguments with match.call(), print it while returning the evaluated expression, and assign it to an object

f1 <- function(expr) {
 print(as.list(match.call()[-1])$expr)
  expr
  }

artichoke <- f1(seq(-5, 5))
#seq(-5, 5)

artichoke <- f1(c(-5, 5))
#c(-5, 5)

If we need it quoted, then wrap with deparse

f1 <- function(expr) {
 print(deparse(as.list(match.call()[-1])$expr))
  expr  

 }

artichoke <- f1(seq(-5, 5))
#[1] "seq(-5, 5)"

Upvotes: 2

Related Questions