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


You are 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

      

+6


source


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


each column is denoted by the second argument in []

, so

my_matrix[,1] + my_matrix[,2] 

      

is all you need.

+1


source







All Articles