When fed only one single number, sample
works like sample.int
(see ?sample
). If you want to make sure it only samples from the vector you give it, you can work with indices and use this construct:
x[sample(length(x))]
This gives you the correct result regardless the length of x
, and without having to add an if
-condition checking the length.
Example:
mylist <- list(
a = 5,
b = c(2,4),
d = integer(0)
)
mysample <- lapply(mylist,function(x) x[sample(length(x))])
> mysample
$a
[1] 5
$b
[1] 2 4
$d
integer(0)
Note : you can replace sample
by sample.int
to get a little speed gain.