Testing Functions in R
Today I have created a custom function to find the mean of a given data frame, I have also compared the results with the inbuild R function "mean".
Theoretically “A function is defined by an
assignment of the form.
> name <- function (arg_1,
arg_2, ...) expression
This expression is used to calculate a value. Value of the expression is the value returned for the function”.(Venables et al., 2022)
Using this expression and formula for the mean which is
defined by the sum of the digits divided by the total number of digits,
I understood that mean function can be expressed as
myMean <- function(assignment2{return(sum(assignment2)/length(assignment2))}
R usually has already existing
functions in its programming language. For example, adding values to the
environment and then calling for mean. Using command mean(assignment2) is
enough to get the result. But, in case if R doesn't have inbuilt designated
tasks, then it can be carried out by defining every single task in the formula. Like
defining values such as
length which includes the total
number of digits we want to add and sum which is the addition of the digits.
So, the Mean can be obtained by calling the other two values we defined, like sum/length.
Data
Frame:
>assignment2
<- c(16, 18, 14, 22, 27, 17, 19, 17, 17, 22, 20, 22)
Inbuilt designated tasks:
When I implemented this code, I got
mean as
>mean(assignment2)
[1] 19.25
If the inbuilt designated task is absent:
I have also implemented this code to get mean:(University
of Florida, 2007)
>s=sum(assignment2)
>n=length(assignment2)
>myMean(assignment2)<- function(assignment2){return(s/n)}
>myMean(assignment2)
When I implemented this code, I got
mean as
[1] 19.25
Through this experiment, I see
that the mean has been calculated accurately through the function created for
calculating the mean.
URL to git repo:https://github.com/VedaVangala/vedas-r-repo/tree/main/Module%202
References
Venables,W.N., Smith,D.M., & R core
team.(2022).An Introduction to R(Version 4.2.2).
URL: https://cran.r-project.org/doc/manuals/r-release/R-intro.pdf
University of Florida. (2007). Writing
Functions Using R.
URL: http://media.news.health.ufl.edu/misc/bolt/Software_R/docs/03_WorkingWithFunctions.pdf
Comments
Post a Comment