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?
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.
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 (%*%).
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 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.
You want prod
:
R> prod(1:3) [1] 6
If your data is all greater than zero this is a safer solution that will not cause compute overflows:
exp(sum(log(x)))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With