[R] Aggregate weights for a unique set of rows
Weiser, Constantin
constantin.weiser at uni-mainz.de
Thu Jun 28 15:06:27 CEST 2012
Hi, all together. I have - a maybe trivial - problem with aggregating a
list of weights.
Here is the problem:
- At first I have set of nodes (X/Y-coordinates) and associated weights,
where the set
of nodes is typically not unique
- I want to get a set of unique nodes and the sum of associated weights
I am grateful for any help
See for example:
# weights:
w <- c(1, 1, 1, 1, 1)
# not unique set of nodes (X/Y-coordinates):
nodes <- matrix(c(1,2,3,4,5,6,1,2,1,4),ncol=2, byrow=T)
desired Result:
#nodes
[,1] [,2]
[1,] 1 2
[2,] 3 4
[3,] 5 6
[4,] 1 4
#weights
2 1 1 1
That is my solution, but it is very slow (typical size of nodes -->
200000x2):
weights <- c(1, 1, 1, 1, 1)
nodes <- matrix(c(1,2,3,4,5,6,1,2,1,4),ncol=2, byrow=T)
## to be replaced by a faster code
drop.index <- duplicated(nodes)
n.unique <- nodes[!drop.index, ]
w.unique <- numeric(length(n.unique[,1]))
lw <- length(weights)
for (i in seq_along(w.unique)){
index <- as.logical(2==rowSums(nodes==matrix(rep(n.unique[i,],lw),byrow
= TRUE, nrow=lw)))
w.unique[i] <- sum(weights[index])
}
##
n.unique
w.unique
^
| X
| /
| /eiser, Constantin
| / Gutenberg University of Mainz, Germany
| * /\ / Chair of Statistics & Econometrics
| \ / \ / Jakob-Welder-Weg 4, 55128 Mainz
| \/ \/ House of Law and Economics II, Room 00-116
| Tel: 0049 6131 39 22715
+--------------------------------------------------------->
More information about the R-help
mailing list