9

I was wondering if there was a way to assign a value and print the value to the console succinctly.

x <- 1:5; x

This is how I would presently do this, but I was wondering if there was a way to do it in one statement.

zx8754
  • 52,746
  • 12
  • 114
  • 209
Michael Clinton
  • 635
  • 1
  • 6
  • 12

1 Answers1

9

You can try:

(x <- 1:5)

or

print(x <- 1:5)

though that won't work for things like

(names(x) <- letters[1:5])

though for that specific example you can do:

(x <- setNames(x, letters[1:5]))
BrodieG
  • 51,669
  • 9
  • 93
  • 146
  • Didn't expect it but `("names<-"(x, letters[1:5]))` prints `x` with its names. – alexis_laz Feb 25 '14 at 09:32
  • @alexis_laz, but unfortunately that doesn't actually set the names for `x`; I think in order for the black magic to work you have to use the `names(x) <- ...` form; or I guess you could do `(x <- "names<-"(x, letters[1:5]))` which is interesting because this gives you a generic mechanism for other replacement methods that don't have a function like `setNames`. – BrodieG Feb 25 '14 at 13:17
  • Hm, I looked into what you said and I got confused.. E.g. see this `x = 1; y = c(1,2); "names<-"(x, "x"); "names<-"(y, c("y1", "y2")); x; y`; `x` does not get a "names" attribute while `y` does. If `x` is named with `names(x) <- ..` then `"names<-"(x, ..)` does change its "names". – alexis_laz Feb 25 '14 at 14:12
  • @alexis_laz, I'm afraid I still don't get any names being set for either `x` or `y` with your code. If I try `names(x) <- "a"; "names<-"(x, "x"); x`, I still get the original names on `x` (i.e. "a") as well. – BrodieG Feb 25 '14 at 14:20
  • 1
    Please see this other **[SO Q/A](http://stackoverflow.com/questions/22022772/why-is-a-length-one-vector-initially-at-nam2)** for more details on the differences @alexis_laz and I were seeing here. – BrodieG Feb 25 '14 at 20:33