Weighted sampling in R

后端 未结 1 720
有刺的猬
有刺的猬 2021-01-01 21:02

I have a data frame data. At each row i have assigned a weight that is in data$ww. Now I would like to make a sample new_data

相关标签:
1条回答
  • 2021-01-01 21:23

    Use the prob argument of sample():

    samp_idx <- sample(seq_len(nrow(data)), nsample, prob=data$ww)
    new_data <- data[samp_idx, ]
    

    Something like this. Running time is

    # user  system elapsed 
    # 0.015   0.000   0.014 
    

    versus your version:

    # user  system elapsed 
    # 4.278   0.007   4.290 
    
    0 讨论(0)
提交回复
热议问题