当前位置: 动力学知识库 > 问答 > 编程问答 >

r - Element wise multiplication of first 4 columns by last 4 columns

问题描述:

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!

网友答案:

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)]))
分享给朋友:
您可能感兴趣的文章:
随机阅读: