Get random sample, calculate divisions, and repeat process 1000 times

Viewed 27

I have a categorical data column (Urban.f) in a dataset (edu2018) and would like to calculate a division and repeat the process 1000 times.

This is the code I have to get a random sample of size 300. It shows me how many cases of "Urban" and "Rural" there is, along with the rest of columns in the dataset. enter image description here

x1 <- sample_n(edu2018, 300, fac = "urban.f")
summary(x1)

I want to calculate the number that appears in "Urban" by the sum of "Urban" + "Rural".

Then, I want to repeat this step 1000 times. I have tried this code that tries to englobe everything I want, but cannot make it work.

edu2018_df <- edu2018$urban.f
n <- 1000
sample_rural <- replicate(n, {edu2018_df <- sample(edu2018, 300, replace = TRUE)
               count(sample_rural = "Urban")/count(sample_rural == "Urban","Rural) * n})

hist(sample_rural)
1 Answers

You could do:

sample_rural <- replicate(1000, sum(sample(edu2018_df, 300, F) == 'Rural')/300)

hist(sample_rural)

enter image description here


Data used

Obviously, we don't have your actual data, so I recreated your vector edu2018_df, which is simply a vector of "Rural" and "Urban"

set.seed(1)
edu2018_df <- sample(c("Rural", "Urban"), 1000, TRUE)
Related