# [R] Multiply

Ivan Krylov kry|ov@r00t @end|ng |rom gm@||@com
Fri Aug 4 17:05:33 CEST 2023

```В Fri, 4 Aug 2023 09:54:07 -0500
Val <valkremk using gmail.com> пишет:

> I want to multiply two  data frames as shown below,
>
> dat1 <-read.table(text="ID, x, y, z
>  A, 10,  34, 12
>  B, 25,  42, 18
>  C, 14,  20,  8 ",sep=",",header=TRUE,stringsAsFactors=F)
>
>  A,  0.25, 0.35
>  B,  0.42, 0.52
>
> Desired result
>
> ID  Index1 Index2
> 1  A 24.58 30.18
> 2  B 35.59 44.09
> 3  C 17.10 21.30

You mean as in matrix multiplication? Nice of you to show the desired
result, otherwise I wouldn't be sure what you meant. You can employ the
matrix multiplication operator %*% if you use as.matrix and omit the
non-numeric parts:

as.matrix(dat1[,-1]) %*% as.matrix(dat2[match(dat1[,1], dat2[,1]),-1])
#      weight weiht2
# [1,]  24.58  30.18
# [2,]  35.59  44.09
# [3,]  17.10  21.30

The [,-1] part drops the 'ID' column and the match() on the first
columns of both data frames ensures the correct row order. Omit the
match(...) if you have a guarantee that the samples appear in the same
order (A, B, C) in both dat1 and dat2.

Once the calculation is done, you can construct a data frame again
using something like data.frame(ID = dat1[,1], Index = multiplication).

--
Best regards,
Ivan

```