Reputation: 965
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!
Upvotes: 4
Views: 292
Reputation: 1708
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
Upvotes: 2