1

Hi I try to have some user-input string, what if the string has quotation marks (don't know single/double)?

Specifically, I want to store some R code in a string, e.g.,

x = 'a'
y = "b"

how do I store this code in a string (later I will use eval(parse(text=x)) to execute it)


Update:

if ask the user to put in the string at readline() prompt, R will automatically fix the quotation marks:

> readline()
123, "4",  '56'
[1] "123, \"4\",  '56'"

I'm looking at how to allow user paste multiple lines

YJZ
  • 3,934
  • 11
  • 43
  • 67
  • 3
    "*later I will use eval to execute it*" Why? R is not a macro language. – thelatemail Jun 28 '17 at 22:45
  • `eval(parse(text=x))` you mean – amonk Jun 28 '17 at 22:57
  • @thelatemail thanks. The specific context is, we have a software where user can execute R script. But the developers told us that we must use `<-` instead of `=`. I try to store my code as a string, and do the replacement, and do `eval(parse(text=x))` (you're right @amonk thanks-) – YJZ Jun 29 '17 at 04:23
  • You can use either to designate it a string, but double quotes are preferred. Here is more information from the R documentation: [https://stat.ethz.ch/R-manual/R-devel/library/base/html/Quotes.html](https://stat.ethz.ch/R-manual/R-devel/library/base/html/Quotes.html) – GraceLight Jun 28 '17 at 22:43

2 Answers2

2

You must either escape the quotes

x = '\'a\''
y = "\"b\""

Or store the string in the alternative of the quotes you want to store

x = "'a'"
y = '"b"'
Conor
  • 441
  • 6
  • 12
  • thanks @Conor - is there a way if you don't know what the user's gonna put in? – YJZ Jun 30 '17 at 15:26
  • What every library you are using to take the input will handle the escaping automatically. – Conor Jul 24 '17 at 08:45
-2

I think you speak about that :-

    x = '"' + "Your String" + '"';
Azhy
  • 704
  • 3
  • 16