I would like to sample from 3 groups of data (rows) in a dataframe according to different probabilities. So for instance the data looks like
group<-c(1,1,1,2,2,3,3)
var1<-c('aa','ab','ac','ba','bb','ca','ce')
var2<-c('aaa','aba','aca','baa','bba','caa','cba')
var3<-c('aab','abb','acb','bab','bbb','cab','ceb')
data<-data.frame(group,var1,var2,var3)
Now I would like to sample (e.g. totoal of 5) from the whole dataframe (get rows) based on different probabilities (for group==1 --> 0.5, group==2 -->0.4, group==3 -->0.1)
Does anyone know how to solve that with R? Help would be much appreciated. Cheers
...
There is probably a more direct way via by
or split
and there are probably better variable names than the ones I am using, but this should work:
set.seed(4)
probs <- c(0.5, 0.4, 0.1)
grp_1Row_prob <- probs / table(data$group)
row_probs <- rep(grp_1Row_prob, times = table(data$group))
row_probs
# [1] 0.1666667 0.1666667 0.1666667 0.2000000 0.2000000 0.0500000 0.0500000
sampled_rows <- sample(1:NROW(data), size = 5, prob = row_probs)
data[sampled_rows, ]
# group var1 var2 var3
# 2 1 ab aba abb
# 5 2 bb bba bbb
# 4 2 ba baa bab
# 1 1 aa aaa aab
# 6 3 ca caa cab
Consider using sample_n
from dplyr
.
library(dplyr)
group<-c(1,1,1,2,2,3,3)
var1<-c('aa','ab','ac','ba','bb','ca','ce')
var2<-c('aaa','aba','aca','baa','bba','caa','cba')
var3<-c('aab','abb','acb','bab','bbb','cab','ceb')
data<-data.frame(group,var1,var2,var3)
sample_n(data, size = 5, weight = group)
# group var1 var2 var3
#7 3 ce cba ceb
#2 1 ab aba abb
#4 2 ba baa bab
#6 3 ca caa cab
#3 1 ac aca acb
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With