So I want to create a function that calculates some mathematical expressions and return a vector with the answers, let's call it my_numeric_vector()
.
Let's say we have the expressions e^(pi/3) and cos(pi/6). I have tried to create a function but as I am fairly new to R I haven't completely got the grip of it. I tried:
my_numeric_vector()
x <- c(exp(pi/3),cos(pi/6))
return my_numeric_vector(x)
However this does not work and I am sure that I should have more code. What I want it to do is to return the answers in vector form, as
[1] 2.84965390823 0.86602540378
or when I run the function
my_numeric_vector()
it should give the calculations directly. So where am I going wrong? I want it to be a simple but a functioning function.
CodePudding user response:
I recommend to just create a variable so that the expression does not need to be evaluated every time we call the function:
# A function without any input argument thus returning always the same result
my_numeric_vector <- function() {
c(exp(pi/3),cos(pi/6))
}
my_numeric_vector()
#> [1] 2.8496539 0.8660254
# a vector in which the value is only calculated once
my_numeric_vector2 <- c(exp(pi/3),cos(pi/6))
my_numeric_vector2
#> [1] 2.8496539 0.8660254
Created on 2021-10-05 by the reprex package (v2.0.1) by the reprex package (v2.0.1)
CodePudding user response:
I don't quite understand the question: Why do you need a function for this task? I simply ran:
X <- c(exp(pi/3), cos(pi/6)); X
And I obtained:
> X <- c(exp(pi/3), cos(pi/6)); X
[1] 2.8496539 0.8660254
Which is what you want. Can you clarify please?