tidyverse / funs

Collection of low-level functions for working with vctrs
Other
34 stars 7 forks source link

sample() and diag() #14

Closed jennybc closed 4 years ago

jennybc commented 7 years ago

Both sample() and diag() are so "flexible" they are hard to program with.

Re: sample(): this might be connected to rthis() (#13). Maybe the smooth bootstrap described there is rsmooth() and the simple resampling discussed here is rthis()?

hadley commented 7 years ago

This makes me think that maybe we need a "scalar" type:

scalar <- function(x) {
  stopifnot(is.vector(x), length(x) == 1)
  structure(x, class = "scalar")
)
hadley commented 4 years ago

I don't think we'd implement diag(), but a better sample() would be useful (esp since sample(mtcars) samples the columns not the rows)

hadley commented 4 years ago
library(vctrs)

sample <- function(x, size, replace = FALSE) {
  idx <- sample.int(vec_size(x), size, replace = replace)
  vec_slice(x, idx)
}

sample(mtcars, 2)
#>                   mpg cyl  disp  hp drat   wt  qsec vs am gear carb
#> Merc 230         22.8   4 140.8  95 3.92 3.15 22.90  1  0    4    2
#> Dodge Challenger 15.5   8 318.0 150 2.76 3.52 16.87  0  0    3    2
sample(mtcars, 2)
#>              mpg cyl  disp  hp drat    wt qsec vs am gear carb
#> Merc 450SLC 15.2   8 275.8 180 3.07 3.780 18.0  0  0    3    3
#> Fiat X1-9   27.3   4  79.0  66 4.08 1.935 18.9  1  1    4    1

Created on 2019-11-28 by the reprex package (v0.3.0)