The sum of the multiplication of two columns of a matrix in R
I am creating a matrix in R using the following,
ncolumns = 3 nrows = 10 my.mat <- matrix(runif(ncolumns*nrows), ncol=ncolumns)
This matrix indicates the coordinates of the point in 3D. How do I calculate the following in R?
sum of x(i)*y(i)
eg. if there is a matrix,
x y z
1 2 3
4 5 6
then output = 1*2 + 4*5
I am trying to learn R. So any help would be really appreciated.
thank
+3
source to share
3 answers
just:
# 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 access 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"])
+2
source to share