0

I have two matrices imported from csv files. They have the same number of rows and columns. I need a third matrix which would be the element-wise subtraction of the two matrices.

t1 <- read.csv("/matrix_1.csv", check.names = FALSE, sep = ",")
t2 <- read.csv("/matrix_2.csv", check.names = FALSE, sep = ",")

t1 looks like this:

Name,A,B,C,D,E
A,10,5,14,3,0
B,5,21,6,1,0
C,14,6,19,6,4
D,3,1,6,7,1
E,0,0,4,1,3

and t2 like this:

Name,A,B,C,D,E
A,4,5,4,3,0
B,5,2,6,1,0
C,1,6,1,6,4
D,3,1,1,7,1
E,0,0,3,1,2

Trying:

t3 = t1 - t2

doesn't work, it raises:

Warning message: In Ops.factor(left, right) : ‘-’ not meaningful for factors

Probably because t1 and t2 contain strings headers for rows and columns (which are important for the rest of the operations).

How would I go about subtracting two matrices without taking into account the strings for each row and column?

smci
  • 32,567
  • 20
  • 113
  • 146
Lucien S.
  • 5,123
  • 10
  • 52
  • 88
  • You should never have read in the dataframe header rows in the first place. Use `read.csv(header=T...)` or `read.csv(skip=1, ...)`. Or else read in as dataframes, then coerce to `as.matrix(t1) - as.matrix(t2)` – smci Oct 22 '15 at 01:21
  • The string header rows are ***column names***, because they're dataframes (not matrices). – smci Oct 22 '15 at 01:23

2 Answers2

2

Just omit the first column. One way to do this is with negative indexing

t3 <- t1[,-1] - t2[,-1]

If needed, you could merge back in the first column

t3 <- cbind(t1[,1, drop=FALSE], t1[,-1] - t2[,-1])

Of course this assumes all your rows already match up.

MrFlick
  • 195,160
  • 17
  • 277
  • 295
2

You should never have read in the dataframe header rows in the first place. Use read.csv(header=T...) or read.csv(skip=1, ...).

Or else read in t1,t2 as dataframes, then coerce to matrices:

as.matrix(t1) - as.matrix(t2)
smci
  • 32,567
  • 20
  • 113
  • 146
  • 1
    What about the first column? It's still there when you do `read.csv(skip = 1, header = FALSE)`. You would need `read.csv(skip = 1, header = FALSE, row.names = 1)`. Then you can subtract the two – Rich Scriven Oct 22 '15 at 02:25
  • In fact, if you just did `read.csv(row.names = 1)` on both it would do the trick nicely, keeping the header and moving the first column to the row names. Then `t1 - t2` works, I've tested it – Rich Scriven Oct 22 '15 at 02:31