"Hands-On Programming with R" book example producing error

I'm working through the O'Reilly Hands-On Programming with R book and hit a small snag that has me confused. This may turn out to be a silly thing, but I couldn't find anything by searching (google, stackoverflow) and I would rather understand it than simply move on.

First, there is a function that simulates a pair of dice being rolled:

roll <- function() {
  die <- 1:6
  dice <- sample(die, size = 2, replace = TRUE)
  sum(dice)
}

but when I try to run the following code to simulate 10,000 rolls and plot the histogram:

rolls <- replicate(10000, roll())
qplot(rolls, binwidth = 1)

I get the following error in RStudio:

> qplot(rolls, binwidth = 1)
Error: Elements must equal the number of rows or 1
Run `rlang::last_error()` to see where the error occurred.

If I do as suggested there, I get this output:

> rlang::last_error()
<error/rlang_error>
Elements must equal the number of rows or 1
Backtrace:
  1. (function (x, ...) ...
  2. ggplot2:::print.ggplot(x)
  4. ggplot2:::ggplot_build.ggplot(x)
  5. ggplot2:::by_layer(function(l, d) l$compute_aesthetics(d, plot))
  6. ggplot2:::f(l = layers[[i]], d = data[[i]])
  7. l$compute_aesthetics(d, plot)
  8. ggplot2:::f(..., self = self)
  9. ggplot2:::as_gg_data_frame(evaled)
 10. ggplot2:::new_data_frame(tibble::as_tibble(x))
Run `rlang::last_trace()` to see the full context.

And if I follow that thread, I get:

> rlang::last_trace()
<error/rlang_error>
Elements must equal the number of rows or 1
Backtrace:
     x
  1. +-(function (x, ...) ...
  2. \-ggplot2:::print.ggplot(x)
  3.   +-ggplot2::ggplot_build(x)
  4.   \-ggplot2:::ggplot_build.ggplot(x)
  5.     \-ggplot2:::by_layer(function(l, d) l$compute_aesthetics(d, plot))
  6.       \-ggplot2:::f(l = layers[[i]], d = data[[i]])
  7.         \-l$compute_aesthetics(d, plot)
  8.           \-ggplot2:::f(..., self = self)
  9.             \-ggplot2:::as_gg_data_frame(evaled)
 10.               \-ggplot2:::new_data_frame(tibble::as_tibble(x))

Thanks in advance.

I copy-pasted your code and it runs fine on my computer... FYI I have R version 3.6.2 and ggplot2 3.3.0

Hmm, my mystery remains, but thank you.

I have R 3.6.3 and ggplot2 3.3.0 as well (but this example only uses qplot anyway).

Ah I spoke too soon. I reran it and now it works. Not sure what was wrong earlier!

(may as well give you the 'solution' checkmark, since after I read your post I tried it again and it worked. Hey, it's magic :slight_smile: cheers)

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.