How to mix rows in R

r

#1

I am currently working on iris data in R when I have used the head command on iris data set
head(iris)
Sepal.Length Sepal.Width Petal.Length Petal.Width Species
1 5.1 3.5 1.4 0.2 setosa
2 4.9 3.0 1.4 0.2 setosa
3 4.7 3.2 1.3 0.2 setosa
4 4.6 3.1 1.5 0.2 setosa
5 5.0 3.6 1.4 0.2 setosa
6 5.4 3.9 1.7 0.4 setosa
As a species I am only getting the setosa as first few rows .I want to mix the rows so I get all species example in first few rows.


#2

@sid100158,

This can be done in various ways, I am listing two of these:

  1. Sort the data set on other parameters, currently it is sorted on Species. You can use the order() function directly.
  2. Select random records using sample function.
    df[sample(nrow(df), 3), ]

Thanks,
Mark


#3

I wrote a quick function that mixes up the data frame by any column you pick. You can also pick how many of each group you want.

mix(df, Species,2)
  Sepal.Length Sepal.Width Petal.Length Petal.Width    Species
1          5.1         3.5          1.4         0.3     setosa
2          4.9         3.1          1.5         0.1     setosa
3          6.2         2.9          4.3         1.3 versicolor
4          5.6         2.7          4.2         1.3 versicolor
5          5.7         2.5          5.0         2.0  virginica
6          7.7         3.8          6.7         2.2  virginica

The function is:

mix <- function(DF,mix.by,each=5) {
  COL <- ifelse(is.character(substitute(mix.by)), mix.by, deparse(substitute(mix.by)))
  out <- do.call(rbind, 
          lapply(split(DF, DF[,COL]), 
                 function(x) {n <- min(each,nrow(x));x[sample(nrow(x),n),]}
                 )
          )
  `rownames<-`(out, NULL)
}