lapioche75 - 5 months ago 31

R Question

I'm trying to do an element wise multiplication of the first 2 columns by the next 2 columns and add the result on the fifth column

for example :

`> x = diag(4)`

[,1] [,2] [,3] [,4] C1*C3 + C2*C4

[1,] 1 0 0 0 1*0 + 0*0

[2,] 0 1 0 0 0*0 + 1*0

[3,] 0 0 1 0 0*1 +0*0

[4,] 0 0 0 1 0*0 +0*1

Thank you!

Answer

You can do this pretty directly in base R.

```
cbind(x, rowSums(x[,1:2] * x[,3:4]))
```

Although going by what you show in your 'results' you are doing every other column which is a simple modification

```
cbind(x, rowSums(x[,c(1,3)] * x[,c(2,4)]))
```