13

If I have a large dataset in R, how can I take random sample of the data taking into consideration the distribution of the original data, particularly if the data are skewed and only 1% belong to a minor class and I want to take a biased sample of the data?

BSMP
  • 4,596
  • 8
  • 33
  • 44
simplyme
  • 221
  • 1
  • 3
  • 7
  • 1
    Import the data, find the weights for your "levels" and let `sample` take care of the rest. It would help if you could narrow your question down (with at least sample data - http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example). – Roman Luštrik Apr 22 '12 at 18:41
  • See also http://stackoverflow.com/questions/2923092/how-do-i-sub-sample-data-by-group-using-ddply – Ben Bolker Apr 24 '12 at 16:14

1 Answers1

22

The sample(x, n, replace = FALSE, prob = NULL) function takes a sample from a vector x of size n. This sample can be with or without replacement, and the probabilities of selecting each element to the sample can be either the same for each element, or a vector informed by the user.

If you want to take a sample of same probabilities for each element with 50 cases, all you have to do is

n <- 50
smpl <- df[sample(nrow(df), 50),]

However, if you want to give different probabilities of being selected for the elements, let's say, elements that sex is M has probability 0.25, while those whose sex is F has prob 0.75, you should do

n <- 50
prb <- ifelse(sex=="M",0.25,0.75)
smpl <- df[sample(nrow(df), 50, prob = prb),]
João Daniel
  • 8,696
  • 11
  • 41
  • 65
  • Unless I'm missing something obvious here, I'm getting `Error in ifelse(sex == "M", 0.25, 0.75) : object 'sex' not found` from trying to run the last example. – Harry Aug 16 '16 at 09:29
  • 2
    I did just get it to work with `prob=ifelse(df$sex == "M", 0.25, 0.75)` in the `sample` function, though. – Harry Aug 16 '16 at 10:31