Quantcast
Channel: Active questions tagged r - Stack Overflow
Viewing all articles
Browse latest Browse all 201839

R : quick way for assigning a value to each member of a group

$
0
0

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 :-)


Viewing all articles
Browse latest Browse all 201839

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>