简体   繁体   中英

Translate dplyr slice_sample function into base R

Just a quick question: how to translate the dplyr function slice_sample into base R? Here is a toy dataset:

y <- rnorm(20)
x <- rnorm(20)
z <- rep(1:4, 5)
w <- rep(1:5, each=4)
dd <- data.frame(id=z,cluster=w,x=x,y=y)

Then I use slice_sample to randomly select 18 cases:

dd %>% slice_sample(n = 18) %>%
  arrange(cluster)

How to translate the dplyr code above into base R without using any packages? Many thanks!

Something like this?

a <- dd[sample(nrow(dd), 18), ]  
b <- a[order(a$cluster), ]

> head(b)
  id cluster            x           y
1  1       1  1.173261588 -0.32704781
2  2       1 -0.008782128  0.40472078
4  4       1  0.635944243 -0.16056411
3  3       1  0.774128998 -0.16587688
5  1       2  0.018583883  0.01382323
6  2       2  2.571984650  0.99070283

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM