R Programming – Functions

Introduction

R programming language functions provide an easy way to develop reusable code.  The structure of R Programming functions is very similar to R expressions.  A few examples in this post will expand on the data set from the R Programming Introduction blog post.  Finally, these examples were run in a working directory of C:\R on a Windows 10 workstation.

R Programming – Functions – Setup

R Framework and RStudio

R Framework and RStudio must be installed on your workstation to run these examples.  More information on how to install and configure R can be found in the R Programming Introduction blog post.

Example Files

  1. Go to the following github repository

https://github.com/mndatascienceexamples/datascienceexamples

  1. Download R-prog-functions.zip into working directory -> C:\R
  2. Extract files into C:\R working directory.

There will three files in the C:\R directory:

nfl_2016_games_allseason.txt – input data file.

R_nflgames_example.R  – R script with environment set up and calling functions commands.

R_nflgames_Functions.R – R script with functions for NFL 2016 season data.

RStudio Setup

After working directory has been setup, open RStudio.  Type the following command from R prompt:

setwd(“C:\\R”)

After working directory is set, then run the two R scripts using R’s source command.

source(“R_nflgames_example.R”)

source(“R_nflgames_Functions.R“)

Calling R Functions in RStudio

R_nflgames_example.R  script has function call commands that can be executed from R prompt.  Simply copy command from the text file and paste into a R prompt.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Blog at WordPress.com.

Up ↑

%d bloggers like this: