I'm trying to iterate through a df with a number of addresses in different neighborhoods, and for each neighborhood I would like to randomly divide each address into one of two equal groups. My df looks roughly like this:
neighborhood <- c("armatage", "armatage", "armatage", "windom", "windom", "windom", "windom")
address <- c("a", "b", "c", "d", "e", "f", "g")
df <- data.frame(address, neighborhood)
but with many more neighborhoods with varying numbers of addresses. Using the randomizr package, so far I have been able to come up with this script, which iterates through each neighborhood name and comes up with a randomized list of 0s and 1s with the length of the number of rows within each neighborhood. The problem seems to be the second for loop, and actually assigning the randomized value to each row
for (i in df$neighborhood)
n <- nrow(df[df$neighborhood == i, ])
z <- complete_ra((n))
for (row in 1:nrow(df[df$neighborhood == i, ]))
df$group[row] <- z[row]
where df$group
is where I would like to store the randomly assigned value. I would greatly appreciate any advice anyone might have. Thanks!
Aucun commentaire:
Enregistrer un commentaire