I am trying to set a random integer within each group of existing ID's. The integers must meet the following conditions: unique, non repeating, and the highest integer for a group of ID's will not be greater than the number of rows with that ID.
I have tried doing this in a for loop, and it works for the first group of ID's, but does not repeat for the next set. I looked at several existing stack overflow questions and other sites which address this to some degree, but still have not been able to get it right. Links below:
Randomly Assign Integers in R within groups without replacement
http://r.789695.n4.nabble.com/Random-numbers-for-a-group-td964301.html
random selection within groups
I need it to be dynamic in the sense that week by week there could be more ID's or fewer ID's. The actual DF has several other columns, but for ease of reproduction they were left out as they are not used.
Example below:
#Desired Output
Groups <- c("A","A","A","A","B","B","B","B","B","B","B","B","C","C","C","C","C","C")
Desired_Integer <- c(1,4,2,3,6,3,1,2,8,5,7,4,5,6,1,4,3,2)
Example <- data.frame(Groups,Desired_Integer)
#Attempted For Loop for Example (assuming Example is a DF with one column, Groups for the For Loop)
Groups <- c("A","A","A","A","B","B","B","B","B","B","B","B","C","C","C","C","C","C")
Example <- as.data.frame(Groups)
for (i in Example$Groups)
{
Example$Desired_Integer <- sample.int(length(which(Example$Groups == i)))
}
Thank you in advance for your help!