• Programming Assignment 2: Lexical Scoping JHU
  • by [email protected]
  • Last updated over 3 years ago
  • Hide Comments (–) Share Hide Toolbars

Twitter Facebook Google+

Or copy & paste this link into an email or IM:

R Programming Week 3 Programming Assignments 2: Lexical Scoping

The following function calculates the mean of the special “vector” created with the above function. However, it first checks to see if the mean has already been calculated. If so, it gets the mean from the cache and skips the computation. Otherwise, it calculates the mean of the data and sets the value of the mean in the cache via the setmean function.

Assignment: Caching the Inverse of a Matrix

Matrix inversion is usually a costly computation and there may be some benefit to caching the inverse of a matrix rather than compute it repeatedly (there are also alternatives to matrix inversion that we will not discuss here). Your assignment is to write

Write the following functions:

makeCacheMatrix: This function creates a special “matrix” object that can cache its inverse. Answer:

A pair of functions that cache the inverse of a matrix.

This function creates a special “matrix” object that can cache its inverse..

cacheSolve: This function computes the inverse of the special “matrix” returned by makeCacheMatrix above. If the inverse has already been calculated (and the matrix has not changed), then the cachesolve should retrieve the inverse from the cache. Computing the inverse of a square matrix can be done with the solve function in R. For example, if X is a square invertible matrix, then solve(X) returns its inverse. Answer:

For this assignment, assume that the matrix supplied is always invertible.

In order to complete this assignment, you must do the following:

Fork the GitHub repository containing the stub R files to create a copy under your own account. Clone your forked GitHub repository to your computer so that you can edit the files locally on your own machine. Edit the R file contained in the git repository and place your solution in that file (please do not rename the file). Commit your completed R file into YOUR git repository and push your git branch to the GitHub repository under your account. Submit to Coursera the URL to your GitHub repository that contains the completed R code for the assignment. In addition to submitting the URL for your GitHub repository, you will need to submit the 40 character SHA-1 hash (as string of numbers from 0-9 and letters from a-f) that identifies the repository commit that contains the version of the files you want to submit. You can do this in GitHub by doing the following:

Going to your GitHub repository web page for this assignment Click on the “?? commits” link where ?? is the number of commits you have in the repository. For example, if you made a total of 10 commits to this repository, the link should say “10 commits”. You will see a list of commits that you have made to this repository. The most recent commit is at the very top. If this represents the version of the files you want to submit, then just click the “copy to clipboard” button on the right hand side that should appear when you hover over the SHA-1 hash. Paste this SHA-1 hash into the course web site when you submit your assignment. If you don’t want to use the most recent commit, then go down and find the commit you want and copy the SHA-1 hash. A valid submission will look something like (this is just an example!)

Matrix inversion is usually a costly computation and there may be some benefit to caching the inverse of a matrix rather than computing it repeatedly (there are also alternatives to matrix inversion that we will not discuss here). Your assignment is to write a pair of functions that cache the inverse of a matrix.

makeCacheMatrix: This function creates a special “matrix” object that can cache its inverse. cacheSolve: This function computes the inverse of the special “matrix” returned by makeCacheMatrix above. If the inverse has already been calculated (and the matrix has not changed), then cacheSolve should retrieve the inverse from the cache. Computing the inverse of a square matrix can be done with the solve function in R. For example, if X is a square invertible matrix, then solve(X) returns its inverse.

Suggested Solution —

##Please include your own comment to explain your code (Required in Rubric)

#Tips for submitting assignment:

  • Download GitHub Desktop
  • Fork the GitHub repository containing the stub R files to create a copy under your own account.
  • Clone your forked GitHub repository to your computer so that you can edit the files locally on your own machine. Clone or Download, revise it in R or Rstudio
  • Commit(or Copy) your completed R file into YOUR git repository and push your git branch to the GitHub repository under your account. *Or you can do pull request on Github.
  • Submit with the URL to your GitHub repository that contains the completed R code for the assignment. Remember to include SHA-1 hash identifier in your submission.

R Programming for Data Science

15 scoping rules of r, 15.1 a diversion on binding values to symbol.

Watch a video of this section

How does R know which value to assign to which symbol? When I type

how does R know what value to assign to the symbol lm ? Why doesn’t it give it the value of lm that is in the stats package?

When R tries to bind a value to a symbol, it searches through a series of environments to find the appropriate value. When you are working on the command line and need to retrieve the value of an R object, the order in which things occur is roughly

  • Search the global environment (i.e. your workspace) for a symbol name matching the one requested.
  • Search the namespaces of each of the packages on the search list

The search list can be found by using the search() function.

The global environment or the user’s workspace is always the first element of the search list and the base package is always the last. For better or for worse, the order of the packages on the search list matters, particularly if there are multiple objects with the same name in different packages.

Users can configure which packages get loaded on startup so if you are writing a function (or a package), you cannot assume that there will be a set list of packages available in a given order. When a user loads a package with library() the namespace of that package gets put in position 2 of the search list (by default) and everything else gets shifted down the list.

Note that R has separate namespaces for functions and non-functions so it’s possible to have an object named c and a function named c() .

15.2 Scoping Rules

The scoping rules for R are the main feature that make it different from the original S language (in case you care about that). This may seem like an esoteric aspect of R, but it’s one of its more interesting and useful features.

The scoping rules of a language determine how a value is associated with a free variable in a function. R uses lexical scoping or static scoping . An alternative to lexical scoping is dynamic scoping which is implemented by some languages. Lexical scoping turns out to be particularly useful for simplifying statistical computations

Related to the scoping rules is how R uses the search list to bind a value to a symbol

Consider the following function.

This function has 2 formal arguments x and y . In the body of the function there is another symbol z . In this case z is called a free variable .

The scoping rules of a language determine how values are assigned to free variables. Free variables are not formal arguments and are not local variables (assigned insided the function body).

Lexical scoping in R means that

the values of free variables are searched for in the environment in which the function was defined .

Okay then, what is an environment?

An environment is a collection of (symbol, value) pairs, i.e.  x is a symbol and 3.14 might be its value. Every environment has a parent environment and it is possible for an environment to have multiple “children”. The only environment without a parent is the empty environment .

A function, together with an environment, makes up what is called a closure or function closure . Most of the time we don’t need to think too much about a function and its associated environment (making up the closure), but occasionally, this setup can be very useful. The function closure model can be used to create functions that “carry around” data with them.

How do we associate a value to a free variable? There is a search process that occurs that goes as follows:

  • If the value of a symbol is not found in the environment in which a function was defined, then the search is continued in the parent environment .
  • The search continues down the sequence of parent environments until we hit the top-level environment ; this usually the global environment (workspace) or the namespace of a package.
  • After the top-level environment, the search continues down the search list until we hit the empty environment .

If a value for a given symbol cannot be found once the empty environment is arrived at, then an error is thrown.

One implication of this search process is that it can be affected by the number of packages you have attached to the search list. The more packages you have attached, the more symbols R has to sort through in order to assign a value. That said, you’d have to have a pretty large number of packages attached in order to notice a real difference in performance.

15.3 Lexical Scoping: Why Does It Matter?

Typically, a function is defined in the global environment, so that the values of free variables are just found in the user’s workspace. This behavior is logical for most people and is usually the “right thing” to do. However, in R you can have functions defined inside other functions (languages like C don’t let you do this). Now things get interesting—in this case the environment in which a function is defined is the body of another function!

Here is an example of a function that returns another function as its return value. Remember, in R functions are treated like any other object and so this is perfectly valid.

The make.power() function is a kind of “constructor function” that can be used to construct other functions.

Let’s take a look at the cube() function’s code.

Notice that cube() has a free variable n . What is the value of n here? Well, its value is taken from the environment where the function was defined. When I defined the cube() function it was when I called make.power(3) , so the value of n at that time was 3.

We can explore the environment of a function to see what objects are there and their values.

We can also take a look at the square() function.

15.4 Lexical vs. Dynamic Scoping

We can use the following example to demonstrate the difference between lexical and dynamic scoping rules.

What is the value of the following expression?

With lexical scoping the value of y in the function g is looked up in the environment in which the function was defined, in this case the global environment, so the value of y is 10. With dynamic scoping, the value of y is looked up in the environment from which the function was called (sometimes referred to as the calling environment ). In R the calling environment is known as the parent frame . In this case, the value of y would be 2.

When a function is defined in the global environment and is subsequently called from the global environment, then the defining environment and the calling environment are the same. This can sometimes give the appearance of dynamic scoping.

Consider this example.

Here, y is defined in the global environment, which also happens to be where the function g() is defined.

There are numerous other languages that support lexical scoping, including

  • Common Lisp (all languages converge to Lisp, right?)

Lexical scoping in R has consequences beyond how free variables are looked up. In particular, it’s the reason that all objects must be stored in memory in R. This is because all functions must carry a pointer to their respective defining environments, which could be anywhere . In the S language (R’s close cousin), free variables are always looked up in the global workspace, so everything can be stored on the disk because the “defining environment” of all functions is the same.

15.5 Application: Optimization

NOTE : This section requires some knowledge of statistical inference and modeling. If you do not have such knowledge, feel free to skip this section.

Why is any of this information about lexical scoping useful?

Optimization routines in R like optim() , nlm() , and optimize() require you to pass a function whose argument is a vector of parameters (e.g. a log-likelihood, or a cost function). However, an objective function that needs to be minimized might depend on a host of other things besides its parameters (like data). When writing software which does optimization, it may also be desirable to allow the user to hold certain parameters fixed. The scoping rules of R allow you to abstract away much of the complexity involved in these kinds of problems.

Here is an example of a “constructor” function that creates a negative log-likelihood function that can be minimized to find maximum likelihood estimates in a statistical model.

Note : Optimization functions in R minimize functions, so you need to use the negative log-likelihood.

Now we can generate some data and then construct our negative log-likelihood.

Now that we have our nLL() function, we can try to minimize it with optim() to estimate the parameters.

You can see that the algorithm converged and obtained an estimate of mu and sigma .

We can also try to estimate one parameter while holding another parameter fixed. Here we fix sigma to be equal to 2.

Because we now have a one-dimensional problem, we can use the simpler optimize() function rather than optim() .

We can also try to estimate sigma while holding mu fixed at 1.

15.6 Plotting the Likelihood

Another nice feature that you can take advantage of is plotting the negative log-likelihood to see how peaked or flat it is.

Here is the function when mu is fixed.

programming assignment 2 lexical scoping

Here is the function when sigma is fixed.

programming assignment 2 lexical scoping

15.7 Summary

  • Objective functions can be “built” which contain all of the necessary data for evaluating the function
  • No need to carry around long argument lists — useful for interactive and exploratory work.
  • Code can be simplified and cleaned up
  • Reference: Robert Gentleman and Ross Ihaka (2000). “Lexical Scope and Statistical Computing,” JCGS , 9, 491–508.

R Programming Assignment 2: Lexical Scoping

Introduction.

This second programming assignment will require you to write an R function is able to cache potentially time-consuming computations. For example, taking the mean of a numeric vector is typically a fast operation. However, for a very long vector, it may take too long to compute the mean, especially if it has to be computed repeatedly (e.g. in a loop). If the contents of a vector are not changing, it may make sense to cache the value of the mean so that when we need it again, it can be looked up in the cache rather than recomputed. In this Programming Assignment will take advantage of the scoping rules of the R language and how they can be manipulated to preserve state inside of an R object.

Example: Caching the Mean of a Vector

In this example we introduce the <<- operator which can be used to assign a value to an object in an environment that is different from the current environment. Below are two functions that are used to create a special object that stores a numeric vector and caches its mean.

The first function, makeVector creates a special “vector”, which is really a list containing a function to

  • set the value of the vector
  • get the value of the vector
  • set the value of the mean
  • get the value of the mean

The following function calculates the mean of the special “vector” created with the above function. However, it first checks to see if the mean has already been calculated. If so, it gets the mean from the cache and skips the computation. Otherwise, it calculates the mean of the data and sets the value of the mean in the cache via the setmean function.

Assignment: Caching the Inverse of a Matrix

Matrix inversion is usually a costly computation and there may be some benefit to caching the inverse of a matrix rather than compute it repeatedly (there are also alternatives to matrix inversion that we will not discuss here). Your assignment is to write a pair of functions that cache the inverse of a matrix.

Write the following functions:

  • makeCacheMatrix: This function creates a special “matrix” object that can cache its inverse.
  • cacheSolve: This function computes the inverse of the special “matrix” returned by makeCacheMatrix above. If the inverse has already been calculated (and the matrix has not changed), then the cacheSolve should retrieve the inverse from the cache.

Computing the inverse of a square matrix can be done with the solve function in R. For example, if X is a square invertible matrix, then solve(X) returns its inverse.

For this assignment, assume that the matrix supplied is always invertible.

My Solution

cachematrix.R:

Testing My Functions

Another useful example.

A good example for getting a better understanding of differences amount formal parameters, local variables and free variables . And it is also helpful for learning the <<- operator.

open.account.R:

Simple tests for open.account function:

More information about Scope .

xmuxiaomo

  • 1. Introduction
  • 2. Example: Caching the Mean of a Vector
  • 3. Assignment: Caching the Inverse of a Matrix
  • 4.1. Functions
  • 4.2. Testing My Functions
  • 5. Another Useful Example

Instantly share code, notes, and snippets.

@Noah-Lee1214

Noah-Lee1214 / R Programming Assignment 2

  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Embed Embed this gist in your website.
  • Share Copy sharable link for this gist.
  • Clone via HTTPS Clone using the web URL.
  • Learn more about clone URLs

@ZilolaEE

ZilolaEE commented Aug 22, 2023

interesting

Sorry, something went wrong.

  • 90% Refund @Courses
  • Data Visualization
  • Statistics in R
  • Machine Learning in R
  • Data Science in R
  • Packages in R

Related Articles

  • Solve Coding Problems
  • R Variables
  • Lexical Scoping in R Programming
  • Dummy Variables in R Programming
  • How to Manually Enter Raw Data in R?
  • goto statement in R Programming
  • R - DataFrame Manipulation
  • Aggregating and analyzing data with dplyr | R Language
  • networkD3 package in R
  • Difference Between R MarkDown and R NoteBook
  • Pie chart using ggplot2 with specific order and percentage annotations
  • Working with Axes in R using ggplot2
  • List of Vectors in R
  • Generalized Linear Models Using R
  • Print htmlwidgets to HTML Result Inside a Function in R
  • Parallel Programming In R
  • Label Encoding in R programming
  • Data mining with caret package
  • Plot Simultaneous and Pointwise Confidence Bands for Linear Regression
  • How to create interactive data visualizations with ggvis

Lexical Scoping vs Dynamic Scoping in R Programming

R is an open-source programming language that is widely used as a statistical software and data analysis tool. R generally comes with the Command-line interface. R is available across widely used platforms like Windows, Linux, and macOS. Also, the R programming language is the latest cutting-edge tool. Scoping Rules of a language are responsible for determining how value will be associated with the free variable in a function in the R language. 

Lexical Scoping

In Lexical Scoping the scope of the variable is determined by the textual structure of a program. Most programming languages we use today are lexically scoped. Even, a human can determine the scope of a variable just by properly reading the code. Below is a code of lexical Scoping in R. 

Output:  

In this example, first, a mapping for a is created. In the next line a function b is defined which returns the value of some a. On line 3, we define a function c, which creates a new mapping for a and then calls b. Note that the assignment on line 4 does not update the definition on line 1 and in the Output value, 1 is returned. 

Dynamic Scoping

In Dynamic scoping, the variable takes the value of the most latest value assigned to that variable  Here, Considering the same above example.  

The output of this code should be 2 according to the rules of Dynamic as the latest value assigned to the variable a is 2. 

Scope in R Language

Sometimes, in R Language code can give the appearance of dynamic Scoping which happens when a function is defined in the global environment and also called from the global environment, resulting in the same environment for defining and calling the environment which can be depicted in the example given below. 

In this example, g is looked up in the environment in which it is defined and hence the value of a is 10. With dynamic scoping, the value of a variable is looked up in the environment in which it is called. In R that environment is known as the parent environment so in function f the value of a will be 2 whereas in g the value will be 10. This may create an illusion of R language being a dynamic language but in reality, it turns out to be Lexical Scope language. Below are some differences between the lexical and dynamic scoping in R programming.

Difference Between Lexical and Dynamic Scoping

Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now !

Please Login to comment...

  • R-Variables
  • abhishek0719kadiyan

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

IMAGES

  1. Programming Assignment 2 Lexical Scoping Coursera Instructions

    programming assignment 2 lexical scoping

  2. Programming-Assignment-2-Lexical-Scoping/Programming Assignment 2

    programming assignment 2 lexical scoping

  3. Programming Assignment 2 Lexical Scoping Coursera Instructions

    programming assignment 2 lexical scoping

  4. GitHub

    programming assignment 2 lexical scoping

  5. Peer-graded Assignment: Programming Assignment 2: Lexical Scoping

    programming assignment 2 lexical scoping

  6. Solved Probem 2

    programming assignment 2 lexical scoping

VIDEO

  1. LEM 212 LEXICAL ASSIGNMENT

  2. 3.3.C++ language constructs with objects and classes: DEFAULT ARGUMENTS || NEC LICENCE EXAM||#nec

  3. programming assignment 2 cosc 1030

  4. Compiler Design

  5. CS304 Object Oriented Programming Assignment 2 Fall 2023 Virtual University of Pakistan

  6. Role of a Lexical Analyzer- Part 7/CS 304 Compiler Design

COMMENTS

  1. Peer-graded Assignment: Programming Assignment 2: Lexical Scoping

    Peer-graded Assignment: Programming Assignment 2: Lexical Scoping -- for Douglas Rubin, BMS Raw. Week 3 programming assignment_b.r This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.

  2. Peer-graded-Assignment-Programming-Assignment-2-Lexical-Scoping

    Solution of the Lexical Scoping assignment Introduction This second programming assignment will require you to write an R function that is able to cache potentially time-consuming computations. For example, taking the mean of a numeric vector is typically a fast operation.

  3. Programming Assignment 2: Lexical Scoping

    Programming Assignment 2: Lexical Scoping For the Coursera course R Programming The following code demonstrates how to use the assessment3.R R script. Lines starting with # are simple comments, lines starting with #> are things printed in the output.

  4. R Programming Week 3 Programming Assignments 2: Lexical Scoping

    RPubs - R Programming Week 3 Programming Assignments 2: Lexical Scoping. by RStudio.

  5. RPubs

    Programming Assignment 2: Lexical Scoping JHU; by [email protected]; Last updated over 3 years ago; Hide Comments (-) Share Hide Toolbars

  6. On coursera R-programming course Assignment 2 Lexical Scoping

    On coursera R-programming course Assignment 2 Lexical Scoping [duplicate] Ask Question Asked 6 years, 10 months ago Modified 6 years, 10 months ago Viewed 7k times Part of R Language Collective 0 This question already has an answer here : R programming: cache the inverse of a matrix (1 answer) Closed 6 years ago.

  7. R Programming Week 3 Programming Assignments 2: Lexical Scoping

    R Programming Week 3 Programming Assignments 2: Lexical Scoping StanLee 9/29/2022. ... Assignment: Caching the Inverse of a Matrix. Matrix inversion is usually a costly computation and there may be some benefit to caching the inverse of a matrix rather than compute it repeatedly (there are also alternatives to matrix inversion that we will not ...

  8. R Programming (JHU Coursera, Course 2)

    Sign in The second course in the data science specialization, "R Programming" is an introductory course teaching users the basics of R. While I did think it went over the basics well, the assignment…

  9. 15 Scoping Rules of R

    Lexical scoping turns out to be particularly useful for simplifying statistical computations Related to the scoping rules is how R uses the search list to bind a value to a symbol Consider the following function. > f <- function(x, y) { + x^2 + y / z + } This function has 2 formal arguments x and y.

  10. Lexical Scoping in R Programming

    Lexical Scoping is a set of rules that helps to determine how R represents the value of a symbol. It is an in-built rule in R which automatically works at the language level. It is mostly used to specify statistical calculations.

  11. scope

    The answer is 1 because 1 is defined in the environment that f is defined in. Had R used dynamic scoping rather than lexical scoping the answer would have been 0 (using the environment of the caller). We can illlustrate how R can emulate dynamic scoping like this: f <- function () eval.parent (quote (x)) g () # 0. ADDED:

  12. Peer-graded Assignment: Programming Assignment 2: Lexical Scoping · GitHub

    Peer-graded Assignment: Programming Assignment 2: Lexical Scoping Raw Week 3 programming assignment_b.r setwd ('C:/Users/rubind1/Documents/Coursera-R') ## ## I simply set the input x as a matrix ## and then set the solved value "s" as a null ## then I changed every reference to "mean" to "solve"

  13. R Programming Course (Johns Hopkins)

    Welcome to Week 2 of R Programming. This week, we take the gloves off, and the lectures cover key topics like control structures and functions. We also introduce the first programming assignment for the course, which is due at the end of the week. ... Programming Assignment 2: Lexical Scoping ...

  14. R Programming Assignment 2: Lexical Scoping

    Introduction 2. Example: Caching the Mean of a Vector 3. Assignment: Caching the Inverse of a Matrix 4. My Solution 5. Another Useful Example 匆忙世间的闲人。

  15. R Programming Assignment 2 : Lexical Scoping--caching the ...

    R Programming Assignment 2. ## R Programming Assignment 2: Lexical Scoping--caching the inverse of a matrix. ## The makeCacheMatrix function creates a special "matrix", ## which is really a list containing a function to. ## 1. set the value of the matrix. ## 2. get the value of the matrix. ## 3. set the value of the inverse of the matrix.

  16. Lexical Scoping vs Dynamic Scoping in R Programming

    Also, the R programming language is the latest cutting-edge tool. Scoping Rules of a language are responsible for determining how value will be associated with the free variable in a function in the R language. Lexical Scoping. In Lexical Scoping the scope of the variable is determined by the textual structure of a program. Most programming ...

  17. GitHub

    This second programming assignment will require you to write an R function that is able to cache potentially time-consuming computations. For example, taking the mean of a numeric vector is typically a fast operation.

  18. R Programming Assignment 2: Lexical Scoping #1556

    Assignment: Programming Assignment 2: Lexical Scoping reetikas Jan 19, 2016. File filter Filter by extension. Filter by extension.R (1) All 1 file type selected Viewed files Clear filters. Conversations. Failed to load comments. Retry Jump to. Jump to file Failed to load files. Retry Diff view ...

  19. Coursers R programming week 3 Assignment Submission and Program

    Coursers R programming week 3 Assignment Submission and Program - YouTube 0:00 / 6:18 This video contains the code for programming assignment-3 and the step by step instructions for...

  20. How do you use "<<-" (scoping assignment) in R?

    Using <<- and assign (x, value, inherits=TRUE) means that "enclosing environments of the supplied environment are searched until the variable 'x' is encountered." In other words, it will keep going through the environments in order until it finds a variable with that name, and it will assign it to that.

  21. mpercot/Programming-Assignment-2-Lexical-Scoping

    Prog Programming Assignment 2: Lexical Scoping. Contribute to mpercot/Programming-Assignment-2-Lexical-Scoping development by creating an account on GitHub.

  22. vijaybarai/Assignment-Programming-Assignment-2-Lexical-Scoping

    GitHub - vijaybarai/Assignment-Programming-Assignment-2-Lexical-Scoping: Assignment: Caching the Inverse of a Matrix vijaybarai / Assignment-Programming-Assignment-2-Lexical-Scoping Public master 1 branch 0 tags Go to file Code vijaybarai Update README.md 342c833 on Sep 10, 2016 8 commits Example.R Add files via upload 6 years ago README.md