Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

r join two lists and sum their values

Tags:

r

I have two lists: x, y

> x
     carlo      monte simulation      model    quantum 
        31         31          9          6          6 
> y
      model      system temperature     quantum  simulation     problem 
         15          15          15          13          13          12

What function should I use to obtain:

simulation     model   quantum
        22        21        19

I tried to merge them like in example but it gives me an error:

merge(x,y,by=intersect(names(x),names(y))) produces:

Error in fix.by(by.x, x) : 'by' must specify uniquely valid columns

There's no argument in that function what to do with values. What would be the best function to use?

intersect(names(x),names(y)) will give the names of resulting list, but how to summarize values together??

like image 318
Peter.k Avatar asked Oct 21 '25 03:10

Peter.k


1 Answers

You can use Map in base R to return a list.

Map("+", x[intersect(names(x),names(y))], y[intersect(names(x),names(y))])
$simulation
[1] 22

$model
[1] 21

$quantum
[1] 19

or mapply to return a named vector which may be more useful.

mapply("+", x[intersect(names(x),names(y))], y[intersect(names(x),names(y))])
simulation      model    quantum 
        22         21         19

Using [intersect(names(x), names(y))] will not only be subset the contents of x and y to those with intersecting names, but will also properly sort the elements for the operation.

data

x <- list(carlo=1, monte=2, simulation=9, model=6, quantum=6)
y <-list(model=15, system=8, temperature=10, quantum=13, simulation=13, problem="no")
like image 98
lmo Avatar answered Oct 24 '25 20:10

lmo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!