I have a data.frame like this:
DqStr <- "Group q Dq SD.Dq
1 -3.0 0.7351 0.0067
1 -2.5 0.6995 0.0078
1 -2.0 0.6538 0.0093
2 -3.0 0.7203 0.0081
2 -2.5 0.6829 0.0094
2 -2.0 0.6350 0.0112"
Dq1 <- read.table(textConnection(DqStr), header=TRUE)
I would like to randomize group membership but only for rows with the same value of Dq1$q
g <-unique(Dq1$q)
Dq2<- data.frame()
for(n in g)
{
Dqq <- Dq1[Dq1$q==n,]
Dqq$Group <-sample(Dqq$Group)
Dq2 <- rbind(Dq2,Dqq)
}
That could also be done with plyr
library(plyr)
ddply(Dq1,.(q), function(x) { x$Group <- sample(x$Group)
data.frame(x)})
as I have to repeat this thousands times I wonder if there are a better (faster) way to do it.