sum of multiplication of two columns of a matrix in R

China☆狼群 提交于 2021-02-05 05:53:23

问题


I am generating a matrix in R using following,

ncolumns = 3
nrows = 10
my.mat <- matrix(runif(ncolumns*nrows), ncol=ncolumns)

This matrix indicates the co-ordinates of a point in 3D. How to calculate following in R?

sum of x(i)*y(i)

e.g. if the matrix is,

x y z
1 2 3
4 5 6

then output = 1*2 + 4*5

I'm trying to learn R. So any help will be really appreciated.

Thanks


回答1:


You're looking for the %*% function.

ncolumns = 3
nrows = 10

my.mat <- matrix(runif(ncolumns*nrows), ncol=ncolumns)

(my.answer <- my.mat[,1] %*% my.mat[,2])

#       [,1]
# [1,] 1.519



回答2:


you simply do:

#  x is the first column; y is the 2nd
sum(my.mat[i, 1] * my.mat[i, 2])

Now, if you want to name your columns, you can refer to them directly

colnames(my.mat) <- c("x", "y", "z")

sum(my.mat[i, "x"] * my.mat[i, "y"])

# or if you want to get the product of each i'th element 
#  just leave empty the space where the i would go
sum(my.mat[ , "x"] * my.mat[ , "y"])



回答3:


each column is designated by the second argument in [], so

my_matrix[,1] + my_matrix[,2] 

is all you need.



来源:https://stackoverflow.com/questions/14917323/sum-of-multiplication-of-two-columns-of-a-matrix-in-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!