Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading