在R中为每个组成员分配值的快速方法:

huangapple go评论78阅读模式
英文:

Quick way for assigning a value to each member of a group in R

问题

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?

英文:

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?

答案1

得分: 5

如组从1开始编号,您可以使用groups向量来索引weights_by_group向量。

weights_ind = weights_by_group[groups]

在我的计算机上,对于2000个个体,这大约需要10微秒。

如果您的组不是数字,您可以使用组标识符命名weights_by_group向量,仍然可以使用groups来索引:

groups = sample(letters[1:n.group], n.tot, replace = TRUE)
weights_by_group = rexp(n.group, rate = 1)
names(weights_by_group) = letters[1:n.group] 

weights_ind = weights_by_group[groups]
英文:

As the groups are numbered starting at 1, you can use the groups vector to index the weights_by_groupvector.

weights_ind = weights_by_group[groups]

On my computer, for 2000 individual, this takes about 10 microseconds.

If your groups were not numeric, you could name the weights_by_group vector with the group identifier, and still use the groups to index:

groups = sample(letters[1:n.group], n.tot, replace = TRUE)
weights_by_group = rexp(n.group, rate = 1)
names(weights_by_group) = letters[1:n.group] 

weights_ind = weights_by_group[groups]

huangapple
  • 本文由 发表于 2020年1月7日 01:01:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/59616126.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定