I have a dataframe that looks something like the example code I've included below. For each ID and Group #, I would like to randomly draw one of the colors (i.e. all rows associated with that color), without replacement, and add it to a new dataframe to be analyzed. I want to create multiple dataframes this way.
require(dplyr)
require(tibble)
df<-data.frame(ID=rep(c('Bravo', 'Charlie', 'Delta', 'Echo'), c(4,4,11,3)),
Group=rep(c(1,2,3,4,1,2,1), c(5,1,1,1,6,5,3)),
Color=rep(c('red','yellow','red','yellow','blue','red','yellow','blue','red','yellow'),c(1,3,5,2,3,2,2,1,1,2)),
Score=c(0.75, 0.9, 0.65, 0.7, 0.55, 0.6, 0.8, 0.9, 0.85, 0.9, 0.8, 0.45, 0.6, 0.65, 0.63, 0.51, 0.7, 0.56, 0.68, 0.87, 0.85, 0.89)
)
To (hopefully) simplify this, I created an additional column "Key" that merges ID and group.
df <- df %>%
add_column(Key=paste(df$ID, df$Group, sep = "_"), .after = 2)
df$Key <- as.factor(df$Key)
So now for each level in "Key," I need to randomly select one of the available colors and generate a new df.
An example for clarity: Bravo has one group and two color subsets in that group. Either the red subset (one row) or the yellow subset (three rows) would be sampled in the new dataframe. Charlie, on the other hand, has only one color subset per group, so for each group 1-4, 'red' would be drawn 100% of the time.
Does anyone have suggestions for how to go about this? Thanks in advance!