Grouped sampling without duplication

Viewed 28

I'm struggeling to find a solution for the following problem. From a dataframe with 384 rows and 11 columns need to be drawn 24 samples ramdomly, each one containing 16 items. Those 16 items also represent the total amount of combinations between factor levels which must be considered within each sample. We have 4 grouping factors in the process: Type, Valence, LT, Gender. All of them comprise 2 factor levels respectively. The dataframe looks essentially like this:

df2 <- data.frame(VNr=c(rep(1:8, 48)),
                 PId=c(rep(1:48, each = 8)), 
                 Gender=rep(c("M", "F"), each=192), 
                 Type=rep(c("E", "S"), each=4, times=48),
                 Valence=rep(c("P", "N"), each = 2, times=96),
                 LT=rep(c("L", "T"), each=1, times=192))

My former approach used dplyr to do the job:

N=24
df3 <- map_dfr(seq_len(N), ~df2 %>% 
                 group_by(Type, Valence, LT, Gender) %>% 
                 slice_sample(n = 1) %>% 
                 mutate(sample_no = .x) %>%
                 ungroup() %>%
                 mutate(resample = duplicated(PId)) %>% 
                 rowwise())

Regarding the grouping, this works flawlessly. However, it produces duplicates, meaning the same PId appearing more than once in single sample, which is not acceptable. How can this be avoided?

LMc proposed a workaround here

Sampling by Group in R with no replacement but the final result cannot contain any repeats as well

Unfortunately, I could not get this to work yet.

Any help on this issue is very much appreciated!

Thanks in advance!

-Marshal

1 Answers

Does this work?

library(tidyverse)

df2 <- tibble(
  VNr=c(rep(1:8, 48)),
  PId=c(rep(1:48, each = 8)), 
  Gender=rep(c("M", "F"), each=192), 
  Type=rep(c("E", "S"), each=4, times=48),
  Valence=rep(c("P", "N"), each = 2, times=96),
  LT=rep(c("L", "T"), each=1, times=192)
)

df2

df2 %>%
  group_by(Type, Valence, LT, Gender) %>%
  mutate(n_rows_initial = n()) %>%
  slice_sample(n = 16, replace = FALSE) %>%
  mutate(n_rows_sampled = n()) %>%
  ungroup()
Related