0

R seems to degrade a list of length 1 to a scalar.

For example:

d=1:3
a=1
b=2
remains = d[c(-a, -b)]
sample(remains, 6, replace=TRUE)

This doesn't work correctly because sample() treats "remains" as a single number, and not a list of 1 element. sample returns values in the range 1:3

if I change the above code so "b=1", then sample() returns as expected.

How to fix this code without adding a special case for length(remains)==1 ?

joeking
  • 2,006
  • 18
  • 29
  • R doesn't have scalars `remains` in your code is a vector of length 1. – John Coleman Jan 22 '18 at 01:50
  • Perhaps, but the problem is the same. sample(N) behaves differently when length(N)==1 vs length(N) > 1 – joeking Jan 22 '18 at 01:51
  • 1
    In addition to the marked duplicate, http://r.789695.n4.nabble.com/using-quot-sample-quot-for-a-vector-of-length-1-td2299330.html suggests many of the same solutions. – josliber Jan 22 '18 at 01:52
  • 3
    Also take a look at `?sample`; there is a comment (and an example introducing a safer function `resample`) that addresses your "issue". – Maurits Evers Jan 22 '18 at 01:53

0 Answers0