18.05 | Spring 2022 | Undergraduate

Introduction to Probability and Statistics

R Tutorial: Functions


We estimate this tutorial will take 10 minutes. It consists of two simple examples of writing functions.

Write your own functions

# R has many built in functions like sin(x), exp(x), print(s). Generally speaking, you won’t write functions on the command line. Rather, they will be put in source files, or in the source pane in R Studio.  
# Here we will give two simple examples of writing our own function.

# You should paste this code into the source window and then choose ‘Source’ under the ‘Code’ menu. Then practice

#Here’s a simple function that squares its argument. 

square_me = function(n) {    
    x = n*n    

# Now you can call this function from the command line 

> square_me(4) 
 [1] 16 

Here’s a function that builds and prints a phrase from some input strings. 

hello_there = function(name, adjective) {     
    phrase = paste("Hello ", name, "! You look ",                     
                    adjective,".", sep="")     
> hello_there("Jerry", "fuzzy")  
 [1] "Hello Jerry ! You look fuzzy ."

Course Info

As Taught In
Spring 2022
Learning Resource Types
Lecture Notes
Problem Sets with Solutions
Exams with Solutions
Activity Assignments with Examples
Exam Materials
Instructor Insights