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

For loop with random variables different person_id in R

Does anyone have an idea create "FOR" loop in R that would repeat all variables choice n times and the only thing that changes is human id (after 16384 rows, where human id = 1, plus another 16384 rows should be with humanid = 2).
I tried to create new data frame where a$humanid<-rep(2,nrow(a)) and combine two tables, but that would be stupid, since I need 100 humans with same variables and different choice.

Here is my code for variables with humanid=1:

a<-expand.grid(price75 = seq(1,0), price100 = seq(1,0),
               price125 = seq(1,0), fuel5 = seq(1,0), fuel15 = seq(1,0),
               fuel25 = seq(1,0), co2_50 = seq(1,0), co2_75 = seq(1,0),
               co2_100 = seq(1,0), range400 = seq(1,0), range700 = seq(1,0),
               range1000 = seq(1,0), avail60 = seq(1,0), avail100 = seq(1,0))
a$humanid<-rep(1,nrow(a)) 

a$choice<-rep(0,nrow(a))
a$choice <- `[<-`(integer(length(a$choice)), sample(length(a$choice), 1), 1)
a$alt <- 1:nrow(a) ```  


Thanks in advance.

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

>Solution :

If I understand the question correctly, a for loop is not necessary. Add humanid to the expand.grid, then take a row sample for each ID, then offset those in order to get each in the correct set of 2^14 rows.

a<-expand.grid(price75 = seq(1,0), price100 = seq(1,0),
               price125 = seq(1,0), fuel5 = seq(1,0), fuel15 = seq(1,0),
               fuel25 = seq(1,0), co2_50 = seq(1,0), co2_75 = seq(1,0),
               co2_100 = seq(1,0), range400 = seq(1,0), range700 = seq(1,0),
               range1000 = seq(1,0), avail60 = seq(1,0), avail100 = seq(1,0),
               humanid = 1:100, choice = 0)
a$choice[sample(2^14, 100, TRUE) + (0:99)*2^14] <- 1
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