I have two vectors, one with the (floating-point) labels, one with the values, e.g
x = c(100.5, 101, 100.5, 102, 99.9, 101, 100.5)
y = c( 3, 1, 1, 2, 0, 1, 0)
The result I'm looking for is the sum for each of the labels, i.e.
res = list("100.5" = 3+1, "101" = 1+1, "102" = 2)
(Ideally "99.9" is not there, as shown above; but if it is there with a count of zero that is also acceptable.)
None of the R idioms I know seem to work, so I tried a C++ style loop: use a for
loop to iterate through y
, grab the value from x
, but then I get stuck on the "does the value already exist in res
" part (to know whether to initialize a new element, or add on to the existing entry). And it just feels so wrong to be doing it this way in R!
By The Way
It needn't be a list
; a named vector, or class table
, are also fine. (If it was C++ I'd be using std::map<double,double>
.) One of the things I need to do next is be able to merge them, and named vectors, at least, go wrong:
res1 = c(3,4,5);names(res1) = c("100.5","101","102")
res2 = c(2,4,6);names(res2) = c("99.5", "100.5", "102")
res3 = c(2,7,4,11);names(res3) = c("99.5", "100.5", "101", "102")
res1 + res2
res1 + res2
does not give me res3
. Doing the same thing with list
objects gives "non-numeric argument to binary operator". (https://stackoverflow.com/a/12897398/841830 shows how to sum table
objects together; a similar approach might work for named vectors...)