0

Why are these vectors different lengths?

length(rep(c(1, 0, 1, 0), times = 500 * c(.55, .45, .05, .95)))
# [1] 1000
length(rep(c(1, 0, 1, 0), times = 500 * c(.55, 1-.55, .05, 1-.05)))
# [1] 999
Eric Green
  • 7,385
  • 11
  • 56
  • 102
  • 2
    It's a precision issue with floating point multiplication. If you `round()` your `times` arguments, they will be the same. It is surprising that the `times` argument of `rep` is behaving this way when you give it non-integers, but really you should always give it integers. – Gregor Thomas Oct 11 '21 at 15:10
  • Got it. Thanks for pointing me to that explainer. `round()` indeed works for me. – Eric Green Oct 11 '21 at 15:13
  • 2
    Looking at the documentation, `rep` uses `as.integer()` on the `times` argument, and `as.integer` uses `trunc` not `round` in its conversion. If you set `x1 = 500 * c(.55, .45, .05, .95)` and `x2 = 500 * c(.55, 1-.55, .05, 1-.05)` and look at `trunc(x1)` and `trunc(x2)` you can see the discrepancy. – Gregor Thomas Oct 11 '21 at 15:14

0 Answers0