Search code examples
rrandomdata.tableshufflegroup

Reshuffling a column by group many times and put the results in new columns


I have the following hypothetical data:

district <- c(1,1,1,1,2,2,2,2,2,3,3,3,3,3,3,3)                                       
village <- c(1,2,3,4,1,2,3,4,5,1,2,3,4,5,6,7)                              
status <- c(1,0,1,0,1,1,1,0,0,1,1,1,1,0,0,0)
datei <- data.table(district, village, status) 

I want to reshuffle status based on district and put the results in new columns. I know how to do it once using the following codes:

datei[, randomstat := sample(status), district]

Now, I want to reshuffle status 1000 times and put the results in new columns. I tried the following codes:

n <- 1000
datei[, paste0("randomstat", 1:n) := replicate(n, list(sample(status), district))]

but failed. Can someone help me with this? Thank you.


Solution

  • You had a typo in your code: district is put inside list, i.e., list(sample(status), district)), which is not correct.


    You have the follow options:

    • Enable simplify = FALSE when using replicate, e.g.,
    datei[, paste0("randomstat", 1:n) := replicate(n, sample(status), simplify = FALSE), district]
    
    • Or, wrap sample(status) with list()
    datei[, paste0("randomstat", 1:n) := replicate(n, list(sample(status))), district]