Home > OS >  Difference Matrix in R
Difference Matrix in R

Time:10-13

I would like to take the difference between two dataframes that are of different lengths and output a matrix in R.

x = data.frame(name=c('a','b','c','d','e'),length=c(5,6,7,8,9))
y = data.frame(name=c('r','t','v'),length=c(10,11,12))

> x
   name   length
1   a      5
2   b      6
3   c      7
4   d      8
5   e      9

> y
   name   length
1   r      10
2   t      11
3   v      12

The result I want is the difference in a matrix. Length of y minus length of x. I also want to keep the names consistent. So something like this:

> 
0  r  t  v
a  5  6  7
b  4  5  6
c  3  4  5
d  2  3  4
e  1  2  3

How can I approach this problem?

CodePudding user response:

This is an outer operation:

outer(setNames(x$length, x$name), setNames(y$length, y$name), FUN=\(x,y) y-x)
#  r t v
#a 5 6 7
#b 4 5 6
#c 3 4 5
#d 2 3 4
#e 1 2 3
  • Related