英文:
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_group
vector.
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]
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论