r - How to sample a dataframe column within a group without reordering of rows? -
i have r dataframe d2 2 columns i.e., "class" , "entry". "class" categorical variable , "entry" continuous given by
d2 class entry 1 1 1 2 2 2 3 3 3 4 4 4 5 1 5 6 2 6 7 3 7 8 4 8 9 1 9 10 2 10 11 3 11 12 4 12 13 1 13 14 2 14 15 3 15 16 4 16 17 1 17 18 2 18 19 3 19 20 4 20
i want sample "entry" column within group given as
ddply(d2,.(class),function(x) x[sample(nrow(x)),]) class entry 1 1 9 2 1 1 3 1 5 4 1 13 5 1 17 6 2 14 7 2 10 8 2 2 9 2 6 10 2 18 11 3 15 12 3 19 13 3 7 14 3 3 15 3 11 16 4 16 17 4 20 18 4 12 19 4 8 20 4 4
it visible desired results obtained order of "class" variable changed compared original data d2. want same output without reordering rows of "class" variable of d2. thanks
here 1 option data.table
library(data.table) setdt(d2)[, entry := sample(entry), = class]
or use ave
base r
d2$entry <- with(d2, ave(entry, class, fun = sample))
Comments
Post a Comment