2

I would like to know how to make R treat an argument as a string even if it does not have quotes. Perhaps with unknown function bar:

foo <- function(x) bar(a))
foo(a abadsf 23)
[1] "a abadsf 23"
9
  • you want to print "a" while there is a variable a defined as "foo" or did I not understand at all ?
    – T_O
    Apr 11, 2014 at 14:37
  • No, I just wrote a="foo" so that it was clear that I did not want to print "foo". Perhaps I should have just given (function(x) print(bar(a)))(a) [1] "a" Apr 11, 2014 at 14:39
  • 2
    that's what I said. You want to print "a" HOWEVER there is a variable a that is defined as "foo". Is it correct ?
    – T_O
    Apr 11, 2014 at 14:40
  • 1
    I'm afraid the part inside foo() will produce a syntax error everytime
    – T_O
    Apr 11, 2014 at 15:17
  • 3
    why exactly do you want to do this?
    – Dason
    Apr 11, 2014 at 15:38

2 Answers 2

7

Is this doing what you want?

printname <- function(x) deparse(substitute(x))
printname(foo)
[1] "foo"
printname(bar)
[1] "bar"

edit: This probably won't be considered acceptable, depending on where these values are coming from, but to include spaces you could try something like:

print.input = function(y=readline()) return(y)

usage in script:

print.input()
input with spaces
[1] "input with spaces"
3
  • My mistake, it is working for that example but not working generally. printname(foo foo) Error: unexpected symbol in "printname(foo foo" Apr 11, 2014 at 15:12
  • @fsmart Sorry, I didn't realise spaces were required at the time. I've added something, but I expect that you have some reason for looking for this capability and that the solution above won't be sufficient for it.
    – ping
    Apr 11, 2014 at 15:36
  • interesting. thank you for the idea but it is not really what I was going after Apr 11, 2014 at 17:27
1

You can use quote, but this doesn't work with spaces.

deparse(quote(abc))
## [1] "abc"
deparse(quote(abc 1))
## Error: unexpected numeric constant in "deparse(quote(abc 1"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.