Search code examples
rcutrandom

randomly allocating factor variables into different groups using r


I have a list of 9 factor variables: item <- c("a","b","c","d","e","f","g","h","i"). I would like to randomly allocate each of the 9 factor variables to 3 groups. I tried this script but it might be a lot of work:

gp1 <- sample(item,3,replace=F)
> gp1
[1] "b" "h" "g"

I also tried the cut function but the variables have to be numeric:

gp <- cut(item, breaks = 3)
Error in cut.default(item, breaks = 3) : 'x' must be numeric

The expected output should look like this but with variables randomly allocated to each group:

grp1  grp1  grp3
d      b     i
c      e     h
a      g     f

Thank you for your help!


Solution

  • Just sample the items and put it in a matrix (which can also be converted to a data.frame if you so desire):

    matrix(sample(item), ncol = 3)
    ##      [,1] [,2] [,3]
    ## [1,] "b"  "d"  "a" 
    ## [2,] "f"  "i"  "e" 
    ## [3,] "h"  "g"  "c" 
    

    If the items won't split to equal lengths, you might consider split, where the splitting variable is based on the shuffling of how many groups you want.

    For instance:

    item <- item[-c(1, 2)]
    split(item, sample(rep(1:3, length.out = length(item))))
    ## $`1`
    ## [1] "c" "e" "i"
    ## 
    ## $`2`
    ## [1] "f" "g"
    ## 
    ## $`3`
    ## [1] "d" "h"
    ##