Statistics with R
- Statistics with R
- R Objects, Numbers, Attributes, Vectors, Coercion
- Matrices, Lists, Factors
- Data Frames in R
- Control Structures in R
- Functions in R
- Data Basics: Compute Summary Statistics in R
- Central Tendency and Spread in R Programming
- Data Basics: Plotting – Charts and Graphs
- Normal Distribution in R
- Skewness of statistical data
- Bernoulli Distribution in R
- Binomial Distribution in R Programming
- Compute Randomly Drawn Negative Binomial Density in R Programming
- Poisson Functions in R Programming
- How to Use the Multinomial Distribution in R
- Beta Distribution in R
- Chi-Square Distribution in R
- Exponential Distribution in R Programming
- Log Normal Distribution in R
- Continuous Uniform Distribution in R
- Understanding the t-distribution in R
- Gamma Distribution in R Programming
- How to Calculate Conditional Probability in R?
- How to Plot a Weibull Distribution in R
- Hypothesis Testing in R Programming
- T-Test in R Programming
- Type I Error in R
- Type II Error in R
- Confidence Intervals in R
- Covariance and Correlation in R
- Covariance Matrix in R
- Pearson Correlation in R
- Normal Probability Plot in R
Functions in R
How to define a function in R
Functions are defined using the function() directive and are stored as R objects just like anything else. In particular, they are R objects of class “function”. Here’s a simple function that takes no arguments simply prints ‘Hi statistics’.
#define the function f <- function() { print("Hi statistics!!!") } #Call the function f()
Output:
[1] "Hi statistics!!!"
Now let’s define a function called standardize, and the function has a single argument x which is used in the body of function.
#Define the function that will calculated standardized score. standardize = function(x) { m = mean(x) sd = sd(x) result = (x - m) / sd result } #Take input for what we want to calculate standardized score. input<- c(40:50) standardize(input) #Call the function
Output:
> standardize(input) #Call the function
[1] -1.5075567 -1.2060454 -0.9045340 -0.6030227 -0.3015113 0.0000000 0.3015113 0.6030227 0.9045340 1.2060454 1.5075567
Here is an example of a simple function in R that takes two arguments and returns their sum:
my_function <- function(a, b) { result <- a + b return(result) }
In the above example, my_function
is the function name, and a
and b
are the parameters passed to the function. The function body is enclosed in curly braces, and it consists of two statements: one that adds a
and b
together and assigns the result to result
, and another that returns the value of result
.
To call this function, you can simply pass in two arguments:
sum_result <- my_function(2, 3) print(sum_result) # Output: 5
In this example, 2
and 3
are the arguments passed to my_function
. The function adds them together and returns the result 5
, which is stored in the variable sum_result
. Finally, the print()
function is used to display the value of sum_result
on the screen.