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

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

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

  1. # Data example
  2. n.group = 10
  3. n.tot = 1000
  4. groups = sample(1:10, n.tot, replace = TRUE)
  5. weights_by_group = rexp(n.group, rate = 1)
  6. weights_ind = rep(NA, n.tot)
  7. for(i in 1:n.tot){
  8. for(j in 1:n.group) {
  9. if(groups[i] == j)
  10. weights_ind[i] = weights_by_group[j]
  11. }
  12. }

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

  1. # Data example
  2. n.group = 10
  3. n.tot = 1000
  4. groups = sample(1:10, n.tot, replace = TRUE)
  5. weights_by_group = rexp(n.group, rate = 1)
  6. weights_ind = rep(NA, n.tot)
  7. for(i in 1:n.tot){
  8. for(j in 1:n.group) {
  9. if(groups[i] == j)
  10. weights_ind[i] = weights_by_group[j]
  11. }}

Which faster function may I use in my case?

答案1

得分: 5

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

  1. weights_ind = weights_by_group[groups]

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

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

  1. groups = sample(letters[1:n.group], n.tot, replace = TRUE)
  2. weights_by_group = rexp(n.group, rate = 1)
  3. names(weights_by_group) = letters[1:n.group]
  4. 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.

  1. 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:

  1. groups = sample(letters[1:n.group], n.tot, replace = TRUE)
  2. weights_by_group = rexp(n.group, rate = 1)
  3. names(weights_by_group) = letters[1:n.group]
  4. 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:

确定