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.
CodePudding user response:
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
CodePudding user response:
Uhm.. Assume there are m
"real" rows, and you want to replicate up to n
ones (so assume m <= n
; Then you can do modulo arithmetic:
m <- 10
n <- 25
(seq_len(n) - 1) %% 10 1
[1] 1 2 3 4 5 6 7 8 9 10 1 2 3 4
[15] 5 6 7 8 9 10 1 2 3 4 5
Where you need the -1
and 1
because of R
indexing from 1
instead of 0
.