I need to attribute a weight to each member of a group.
I have made the following loop to create the weights_ind
vector (vector of individual weights), but my loop is too slow (2 seconds for 2000 individuals) :
# Data example
n.group = 10
n.tot = 1000
groups = sample(1:10, n.tot, replace = TRUE)
weights_by_group = rexp(n.group, rate = 1)
weights_ind = rep(NA, n.tot)
for(i in 1:n.tot){
for(j in 1:n.group) {
if(groups[i] == j)
weights_ind[i] = weights_by_group[j]
}}
Which faster function may I use in my case ?
(sorry if a similar question was already asked. Please, tell me if it's a duplicate)
Thanks for any suggestion :-)