I want to write a function that, given a vector v computes the product of all the entries in v. (There is a function in R that does this, but I want to write one myself.)
I tried however how can I get for product of any elements in a vector?
product <- function(v){
out <- 1
for(i in 1:length(v)){
out <- out*v[i]
}
out
}
If you use
...as the argument to your function, you can pass it several objects or just one. Inside the function, you can convert to a list and useReduceto apply a function (*) recursively to the list. If you combinelist,unlistandas.listyou can make this very general. The following will work with a vector, or with 2 or more numbers, or a mixture of vectors and single numbers.