2

Does anyone know how $ is interpreted within an inline call to rscript?

In the example below, I am trying to get z to be the "a" element within the x list. However, z=x$a gives me x instead of the element of the list.

> Rscript -e "x = list(a=c(1,2,3), b=c(4,5,6)); z = x$a; print(z); print(\"z$a\")"
$a
[1] 1 2 3

$b
[1] 4 5 6

[1] "z"

Notice that even in the print statement, the $ causes somewhat obscure behavior. I would have expected this to print z$a, but it prints z instead.

Two questions:

  1. How exactly is "$" interpreted within a string used as inline code to Rscript?
  2. How can I refer to an element in a list within inline code passed to rscript?
W7GVR
  • 1,990
  • 1
  • 18
  • 24
  • 1
    This likely has more to do with your shell than Rscript. What shell are you running? Sounds like the value is being interpreted before Rscript even sees it. – MrFlick May 18 '15 at 18:18
  • @MrFlick: I am using bash – W7GVR May 18 '15 at 18:19
  • 1
    Then this is a problem with bash doing variable substitution on your string. I don't use bash myself but i think you can prevent expansion with single quotes: `Rscript -e 'x = list(a=c(1,2,3), b=c(4,5,6)); z = x$a; print(z); print ("z$a")'` – MrFlick May 18 '15 at 18:24
  • @MrFlick: Thanks. Do I understand it correctly that bash is substituting $a by the value of the shell variable a, which, since it is not defined, is defaulted to $a=""? – W7GVR May 18 '15 at 19:21
  • Yes, that's consistent with your results. (I don't use bash as my primary shell so i'm not as familiar with what's returned for undefined variables) – MrFlick May 18 '15 at 19:25

2 Answers2

1

To answer you second question, you could do x[['a']]

Quinn Weber
  • 927
  • 5
  • 10
  • Thanks for the alternative: much cleaner than using \$ and, likely, less shell specific. – W7GVR May 19 '15 at 10:42
0

It seems that using \$ instead of $ in the inline code does the trick.

>/lrlhps/apps/R/R-3.1.1/bin/Rscript -e "x = list(a=c(1,2,3), b=c(4,5,6)); z = x\$a; print(z); print(\"z\$a\")"
[1] 1 2 3
[1] "z$a"

Still, does anyone what "$" does?

W7GVR
  • 1,990
  • 1
  • 18
  • 24