How to sample a dataframe column within a group without reordering of rows?

Previous Topic Next Topic
 
classic Classic list List threaded Threaded
1 message Options
Reply | Threaded
Open this post in threaded view
|

How to sample a dataframe column within a group without reordering of rows?

vinodsingh
This post has NOT been accepted by the mailing list yet.
I have a R dataframe df with two columns i.e., "class" and "entry". Where "class" is categorical variable and "entry" is continuous given by

> set.seed(11)
> df=data.frame(class = rep(c(1,2,3,4), 5), entry=sample(1:50,20))
> df
   class entry
1      1    14
2      2     1
3      3    25
4      4    49
5      1     3
6      2    43
7      3     4
8      4    13
9      1    37
10     2     6
11     3     8
12     4    18
13     1    35
14     2    32
15     3    27
16     4    21
17     1    17
18     2    11
19     3    41
20     4    15

I Now want to sample "entry" column within the a group given as

> library(plyr)
> ddply(df, .(class),function(x) x[sample(nrow(x)),])
   class entry
1      1    13
2      1    39
3      1     2
4      1    25
5      1     4
6      2     6
7      2    43
8      2    32
9      2     9
10     2    35
11     3    42
12     3    41
13     3    26
14     3    50
15     3    23
16     4     7
17     4    19
18     4    20
19     4    21
20     4    37

It is clearly visible that desired results are obtained but order of the "class" variable is also changed compared to original data d2. I want to get same output without reordering rows of "class" variable of d2. Thanks


### I  also tried data.table library given on a forum ####

randomise_frag <- function(data) {
  library(data.table)
  data1 <- as.data.table(data)
  v1 <- data1[, sample(.I), by = class]$V1
  print(v1)
  data1[, entry := entry[v1]][]
  }

randomise_frag(df)

#####

This trick is also not giving desired output. If you will run this code steps you will find v1 is giving sampled induces for each class but entries get clustered for each class and these clustered induces are not in order as i desired. Thankyou