I have the following R functions which I want to use to obtain the sum, sum of squares and sum of cubes of any numeric vector:
Functions Corrected
ss <- function(x){
`%dopar%` <- foreach::`%dopar%`
foreach::foreach(i = x, .combine = "+") %dopar% {i}
}
sss <- function(x){
`%dopar%` <- foreach::`%dopar%`
foreach::foreach(i = x, .combine = "+") %dopar% {i^2}
}
ssq <- function(x){
`%dopar%` <- foreach::`%dopar%`
foreach::foreach(i = x, .combine = "+") %dopar% {i^3}
}
which I want to produce the sum of the vector, the sum of the square of the vector and the sum of the cube of the same vector. I want it to print the three results once I run just one function with the will be contained in the R package documentation.
I know how to write an R package with just one function for just one task by documenting the R folder and its files and also DESCRIPTION file while roxygen2
with devtools
do the rest for me.
I want
If x <- c(1, 2) I want something like this format.
ss sss qss
3 5 9
with just a function from the package.
Please state the vector you are using with your output.
EDIT: i've changed the code so that the output is a vector instead of a list.
You can combine your functions into a single function. Here's an example:
sums <- function(x, methods = c("sum", "squaredsum", "cubedsum")){
output <- c()
if("sum" %in% methods){
output <- c(output, ss = ss(x))
}
if("squaredsum" %in% methods){
output <- c(output, sss = sss(x))
}
if("cubedsum" %in% methods){
output <- c(output, ssq = ssq(x))
}
return(output)
}
by default, all three of your functions are called and the results are returned in a list.
You can specify just one or more of the functions, in that case it will only return the outputs of the called functions.
In your documentation, you can now treat each of the possible methods as variable that can be set.'
EDIT
there's a mistake in your cube function. a cube is not taken by i***2
. It's i**3
. The correct function is:
ssq <- function(x){
`%dopar%` <- foreach::`%dopar%`
foreach::foreach(i = x*x*x, .combine = "+") %dopar% {i**3}
}