R-element matrix subtraction

I have two matrices from 1 column of different lengths. Both matrices have row names in common and other row names that are unique to each (and may not be in the same order). How to subtract two of them to make sure that each common element is subtracted from each other? eg:

> mat1
  [,1]
a    1
b    2
c    3
d    4
e    5
f    6

> mat2
  [,1]
x    1
a    2
y    3
b    4

> mat3
  [,1]
a    -1
b    -2
c    3
d    4
e    5
f    6
x    -1
y    -3

where mat3 <- mat1 - mat2
+4
source share
2 answers

Try the following:

 #creating your matrices
 mat1<-matrix(1:6,ncol=1,dimnames=list(letters[1:6],NULL))
 mat2<-matrix(1:4,ncol=1,dimnames=list(c("x","a","y","b"),NULL))
 #getting the unique rownames
 rows<-unique(c(rownames(mat1),rownames(mat2)))
 #creating an "empty" mat3
 mat3<-matrix(0,nrow=length(rows),ncol=1,dimnames=list(rows,NULL))
 #filling values
 mat3[rownames(mat1),]<-mat1
 mat3[rownames(mat2),]<-mat3[rownames(mat2),]-mat2
+4
source

My advice is to avoid using outlet names. Rownames are difficult to manage because one variable (rowname) is handled differently than others. This violates the principles of accurate data .

dplyr::add_rownames(), :

library(dplyr)

< >

mat1 <- matrix(1:6, ncol = 1, dimnames = list(letters[1:6]))
mat2 <- matrix(1:4, ncol = 1, dimnames = list(c("x", "a", "y", "b")))

data.frame :

d1 <- add_rownames(data.frame(mat1), var = "name")
d2 <- add_rownames(data.frame(mat2), var = "name")

:

d <- merge(d1, d2, by = "name", all = TRUE)

d %>%
  rowwise() %>%
  mutate(result = sum(mat1, -mat2, na.rm = TRUE))
+1

All Articles