Thread: calculate difference of two matrix in r

1. calculate difference of two matrix in r

Hi all, I want to calculate the difference of two matrix in r, now I have some problems of that.
Code:
``x <- read.csv("x.csv")``
Code:
``````TI/BI	A	D	E
OI	-0.3158	-0.0194	0.0449
GT	-0.3247	-0.4234	-0.31
WE	-0.1326	-0.6231	-0.5924
BG	0.6237	0.3876	0.5241
RV	0.2647	0.3683	0.5358
CT	0.3385	0.1431	0.2379
IP	0.1899	0.1741	0.2539
QM	-0.3461	0.1666	0.1464
EX	-0.4336	-0.0127	-0.117
TV	0.0075	-0.2751	-0.2307``````
Code:
``y <- read.csv("y.csv")``
Code:
``````TI/BI	A	D	E
OI	-0.4382	0.2187	-0.1043
GT	0.9737	0.7943	0.8363
WE	0.5619	0.0856	0.0462
BG	0.2219	0.5842	0.1784
RV	0.3077	-0.282	-0.0732
CT	0.6951	0.0086	0.4691
IP	-0.2296	-0.8322	-0.5028
QM	-0.2933	0.2162	0.2169
EX	-0.198	-0.2289	-0.5206
TV	-0.5646	-0.3299	-0.7327``````
Code:
``````>A <- apply(x[,c(2:4)],1,as.numeric)
>B <- apply(y[,c(2:4)],1,as.numeric)
>Distance <- dist(A,B, method="manhattan")
>write.csv(Distance,file="Distancet.csv",row.names=TRUE)``````
Code:
``````Error in as.data.frame.default(x[[i]], optional = TRUE) :
cannot coerce class '"dist"' into a data.frame``````
and then I tried another way,
Code:
``````>Distance <- c(A-B)
>write.csv(Distance,file="Distance.csv",row.names=TRUE)``````
Code:
``````
1	0.1224
2	-0.2381
3	0.1492
4	-1.2984
5	-1.2177
6	-1.1463
7	-0.6945
8	-0.7087
9	-0.6386
10	0.4018
11	-0.1966
12	0.3457
13	-0.043
14	0.6503
15	0.609
16	-0.3566
17	0.1345
18	-0.2312
19	0.4195
20	1.0063
21	0.7567
22	-0.0528
23	-0.0496
24	-0.0705
25	-0.2356
26	0.2162
27	0.4036
28	0.5721
29	0.0548
30	0.502``````
The result is like that above, I can not well know what the differences.
the result i want is like that as follows(I calculate that in excel)
Code:
``````TI/BI	A	D	E
OI	0.1224	-0.2381	0.1492
GT	-1.2984	-1.2177	-1.1463
WE	-0.6945	-0.7087	-0.6386
BG	0.4018	-0.1966	0.3457
RV	-0.043	0.6503	0.609
CT	-0.3566	0.1345	-0.2312
IP	0.4195	1.0063	0.7567
QM	-0.0528	-0.0496	-0.0705
EX	-0.2356	0.2162	0.4036
TV	0.5721	0.0548	0.502``````
Would you please give me any useful information?
Thanks very much for your attention.

2. Re: calculate difference of two matrix in r

Define "difference"?

Every element in matrix 1 subtracted from the corresponding element in matrix 2?

Or some kind of set theory thing?

3. The Following User Says Thank You to derksheng For This Useful Post:

scyxr (07-16-2012)

4. Re: calculate difference of two matrix in r

"difference":VALUE1(ij)-VALUE2(ij),
"1","2"represents matrix 1, matrix 2 separately;
"i","j"represents the row, column in each matrix.

5. Re: calculate difference of two matrix in r

Just do A-B instead of c(A-B).

6. The Following User Says Thank You to Dason For This Useful Post:

scyxr (07-16-2012)

Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts