Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

multiplying all elements of a vector in R

Tags:

r

I want a function to return the product of all the values in a vector, like sum but with multiplication instead of addition. I expected this to exist already, but if it does I can't find it. Here's my solution:

product <- function(vec){     out <- 1     for(i in 1:length(vec)){          out <- out*vec[i]     }     out } 

This behaves the way I want it to. For example:

> product(1:3) [1] 6 

Is there a better way of doing this, either with an existing function or through an improvement to this custom one?

like image 824
Fojtasek Avatar asked Jun 21 '10 18:06

Fojtasek


People also ask

How do you multiply all values in a vector in R?

Data Visualization using R Programming To multiply all values in a list by a number, we can use lapply function. Inside the lapply function we would need to supply multiplication sign that is * with the list name and the number by which we want to multiple all the list values.

How do you multiply elements in an array in R?

In R the asterisk (*) is used for element-wise multiplication. This is where the elements in the same row are multiplied by one another. We can see that the output of c*x and x*c are the same, and the vector x doubles matrix c. In R percent signs combined with asterisks are used for matrix multiplication (%*%).

Can you multiply a vector by components?

To multiply a vector by a scalar, multiply each component by the scalar. If →u=⟨u1,u2⟩ has a magnitude |→u| and direction d , then n→u=n⟨u1,u2⟩=⟨nu1,nu2⟩ where n is a positive real number, the magnitude is |n→u| , and its direction is d .

How do you multiply a sequence in R?

How to multiply vector values in sequence with columns of a data frame in R? First of all, create a data frame. Then, create a vector. After that, use t function for transpose and multiplication sign * to multiply vector values in sequence with data frame columns.


2 Answers

You want prod:

R> prod(1:3) [1] 6 
like image 54
rcs Avatar answered Oct 04 '22 06:10

rcs


If your data is all greater than zero this is a safer solution that will not cause compute overflows:

exp(sum(log(x))) 
like image 30
geotheory Avatar answered Oct 04 '22 07:10

geotheory