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.
  • Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
  • Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand
  • OverflowAI GenAI features for Teams
  • OverflowAPI Train & fine-tune LLMs
  • Labs The future of collective knowledge sharing
  • About the company Visit the blog

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Get early access and see previews of new features.

On coursera R-programming course Assignment 2 Lexical Scoping [duplicate]

I'm Using Win7 64x Rstudio Version 3.3.2.

The following functions is assignmet2 solution that other people submitted.

First in the function makeCacheMatrix, why does 'set function' use variable 'y'? Is it simply used to tell us how to use '<<-'?

Secondly, In 'get function', why is variable 'x' followed by the parentheses of the function? ( 'setInverse function - inv<<-inverse' , 'getInverse function - inv' are the same. )

JeongHansol's user avatar

2 Answers 2

x <<- y creates x , which is then retrieved by get() . Note that get is also a base function and is being overwritten here. I would advocate in avoiding this, even though it's confined to a function. An ad hoc solution would be to reach base get function through base::get .

Line get <- function() x is a "short" version of

Short version will work if you have only one line or separate statements using ; . The biggest beef I have with this piece of code is no use of argument. This may be fine with Java or some other language, but I don't consider that an R way. Modifying objects like this can lead to unintended behavior which could lead to painstaking debugging.

setInverse and getInverse are not the same. What they do is set inverse or get it.

Roman Luštrik's user avatar

  • Thanks to your detailed explanation, I understand the problem. Thank you very much. :) –  JeongHansol Commented Mar 29, 2017 at 12:59

You know that the goal of this task is to create a super matrix that can store it's content and it's inverse as well. So it has to have 2 variable x the matrix, and inv the inverse. Each variable has 2 functions set and get . So, set is a function that takes an argument and do something inside it, in this code set takes y as an argument (dummy variable could be any other name) and assign it to the matrix x . The same for inv .

This will make the only access for these variables is through set and get .

Note that:(R documentation) The operators <<- and ->> are normally only used in functions, and cause a search to be made through parent environments for an existing definition of the variable being assigned

Now, if we want to use this function:

Fadwa's user avatar

  • 1 I understand how to use the operator '<<-' for your help. Thank you very much :) –  JeongHansol Commented Mar 29, 2017 at 13:23
  • glad i can help :). This specialization is very useful I am currently taking it. Good luck. –  Fadwa Commented Mar 29, 2017 at 13:29

Not the answer you're looking for? Browse other questions tagged r or ask your own question .

  • Featured on Meta
  • Upcoming sign-up experiments related to tags
  • The return of Staging Ground to Stack Overflow
  • Policy: Generative AI (e.g., ChatGPT) is banned
  • Should we burninate the [lib] tag?
  • What makes a homepage useful for logged-in users

Hot Network Questions

  • Will shading an AC condenser reduce cost or improve effectiveness?
  • Proof/Reference to a claim about AC and definable real numbers
  • C# Linked List implementation
  • Word order of 1 Corinthians 1:24
  • Why do many philosophers consider a past-eternal universe to be self-explanatory but not a universe that began with no cause?
  • Lines of intersections in a parabola
  • How to turn a desert into a fertile farmland with engineering?
  • Why is ACAT not identifying the difference between 2 bridge sites on a surface slab?
  • Historically are there any documented attempts at finding algorithms that are asymptotically faster than the FFT for the Discrete Fourier Transform?
  • sample size in chi-squared test
  • Co-authors with little contribution
  • Is "ROW_NUMBER() OVER(ORDER BY xml.node)" well defined?
  • What is the mode of operation of a Hobb's meter?
  • Vespertide affairs
  • Exception handling: 'catch' without explicit 'try'
  • Is this professor being unnecessarily harsh or did I actually make a mistake?
  • Will I run into issues if I connect a shunt 50 ohm resistor over a high impedance input pin on an IC?
  • What's the meaning of "nai gar"?
  • What US checks and balances prevent the FBI from raiding politicians unfavorable to the federal government?
  • Should mail addresses for logins be stored hashed to minimize impact of data loss?
  • What is a quarter in 19th-century England converted to contemporary pints?
  • Can I replace a GFCI outlet in a bathroom with an outlet having USB ports?
  • Output the Steiner system S(5,8,24)
  • Can a video game developer restrict how people stream game content?

coursera r programming assignment 2 lexical scoping

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
(x = numeric()) {
m <- NULL
set <- function(y) {
x <<- y
m <<- NULL
}
get <- function() x
setmean <- function(mean) m <<- mean
getmean <- function() m
list(set = set, get = get,
setmean = setmean,
getmean = getmean)
}

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.


m <- x$getmean()
if(!is.null(m)) {
message("getting cached data")
return(m)
}
data <- x$get()
m <- mean(data, ...)
x$setmean(m)
m
}

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:


## 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.
## Below are a pair of functions that are used to create a special object that
## stores a matrix and caches its inverse.

## This function creates a special "matrix" object that can cache its inverse.

makeCacheMatrix <- function(x = matrix()) {
inv <- NULL
set <- function(y) {
x <<- y
inv <<- NULL
}
get <- function() x
setInverse <- function(inverse) inv <<- inverse
getInverse <- function() inv
list(set = set,
get = get,
setInverse = setInverse,
getInverse = getInverse)
}


## This function computes the inverse of the special "matrix" created by
## makeCacheMatrix above. If the inverse has already been calculated (and the
## matrix has not changed), then it should retrieve the inverse from the cache.

cacheSolve <- function(x, ...) {
## Return a matrix that is the inverse of 'x'
inv <- x$getInverse()
if (!is.null(inv)) {
message("getting cached data")
return(inv)
}
mat <- x$get()
inv <- solve(mat, ...)
x$setInverse(inv)
inv
}

Testing My Functions

("ProgrammingAssignment2/cachematrix.R")
> my_matrix <- makeCacheMatrix(matrix(1:4, 2, 2))
> my_matrix$get()
[,1] [,2]
[1,] 1 3
[2,] 2 4
> my_matrix$getInverse()
NULL
> cacheSolve(my_matrix)
[,1] [,2]
[1,] -2 1.5
[2,] 1 -0.5
> cacheSolve(my_matrix)
getting cached data
[,1] [,2]
[1,] -2 1.5
[2,] 1 -0.5
> my_matrix$getInverse()
[,1] [,2]
[1,] -2 1.5
[2,] 1 -0.5
> my_matrix$set(matrix(c(2, 2, 1, 4), 2, 2))
> my_matrix$get()
[,1] [,2]
[1,] 2 1
[2,] 2 4
> my_matrix$getInverse()
NULL
> cacheSolve(my_matrix)
[,1] [,2]
[1,] 0.6666667 -0.1666667
[2,] -0.3333333 0.3333333
> cacheSolve(my_matrix)
getting cached data
[,1] [,2]
[1,] 0.6666667 -0.1666667
[2,] -0.3333333 0.3333333
> my_matrix$getInverse()
[,1] [,2]
[1,] 0.6666667 -0.1666667
[2,] -0.3333333 0.3333333

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:

.account <- function(total) {
list(
deposit = function(amount) {
if(amount <= 0)
stop("Deposits must be positive!\n")
total <<- total + amount
cat(amount, "deposited. Your balance is", total, "\n\n")
},
withdraw = function(amount) {
if(amount > total)
stop("You don't have that much money!\n")
total <<- total - amount
cat(amount, "withdrawn. Your balance is", total, "\n\n")
},
balance = function() {
cat("Your balance is", total, "\n\n")
}
)
}

Simple tests for open.account function:

.account(100)
> mm <- open.account(200)
> peter$withdraw(30)
30 withdrawn. Your balance is 70

> peter$balance()
Your balance is 70

> mm$balance()
Your balance is 200

> peter$deposit(50)
50 deposited. Your balance is 120

> peter$balance()
Your balance is 120

> peter$withdraw(500)
Error in peter$withdraw(500) : You don't have that much money!
> mm$balance()
Your balance is 200

> mm$withdraw(12)
12 withdrawn. Your balance is 188

> mm$balance()
Your balance is 188

> peter$balance()
Your balance is 120

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

Johns Hopkins University

R Programming

This course is part of multiple programs. Learn more

This course is part of multiple programs

Roger D. Peng, PhD

Instructors: Roger D. Peng, PhD +2 more

Instructors

Instructor ratings

We asked all learners to give feedback on our instructors based on the quality of their teaching style.

Sponsored by Johns Hopkins University

714,777 already enrolled

(22,206 reviews)

Recommended experience

Intermediate level

Familiarity with regression is recommended.

What you'll learn

Understand critical programming language concepts

Configure statistical programming software

Make use of R loop functions and debugging tools

Collect detailed information using R profiler

Details to know

coursera r programming assignment 2 lexical scoping

Add to your LinkedIn profile

See how employees at top companies are mastering in-demand skills

Placeholder

Build your subject-matter expertise

  • Learn new concepts from industry experts
  • Gain a foundational understanding of a subject or tool
  • Develop job-relevant skills with hands-on projects
  • Earn a shareable career certificate

Placeholder

Earn a career certificate

Add this credential to your LinkedIn profile, resume, or CV

Share it on social media and in your performance review

Placeholder

There are 4 modules in this course

In this course you will learn how to program in R and how to use R for effective data analysis. You will learn how to install and configure software necessary for a statistical programming environment and describe generic programming language concepts as they are implemented in a high-level statistical language. The course covers practical issues in statistical computing which includes programming in R, reading data into R, accessing R packages, writing R functions, debugging, profiling R code, and organizing and commenting R code. Topics in statistical data analysis will provide working examples.

Week 1: Background, Getting Started, and Nuts & Bolts

This week covers the basics to get you started up with R. The Background Materials lesson contains information about course mechanics and some videos on installing R. The Week 1 videos cover the history of R and S, go over the basic data types in R, and describe the functions for reading and writing data. I recommend that you watch the videos in the listed order, but watching the videos out of order isn't going to ruin the story.

What's included

28 videos 9 readings 1 quiz 7 programming assignments

28 videos • Total 129 minutes

  • Installing R on a Mac • 1 minute • Preview module
  • Installing R on Windows • 3 minutes
  • Installing R Studio (Mac) • 1 minute
  • Writing Code / Setting Your Working Directory (Windows) • 7 minutes
  • Writing Code / Setting Your Working Directory (Mac) • 7 minutes
  • Introduction • 1 minute
  • Overview and History of R • 16 minutes
  • Getting Help • 13 minutes
  • R Console Input and Evaluation • 4 minutes
  • Data Types - R Objects and Attributes • 4 minutes
  • Data Types - Vectors and Lists • 6 minutes
  • Data Types - Matrices • 3 minutes
  • Data Types - Factors • 4 minutes
  • Data Types - Missing Values • 2 minutes
  • Data Types - Data Frames • 2 minutes
  • Data Types - Names Attribute • 1 minute
  • Data Types - Summary • 0 minutes
  • Reading Tabular Data • 5 minutes
  • Reading Large Tables • 7 minutes
  • Textual Data Formats • 4 minutes
  • Connections: Interfaces to the Outside World • 4 minutes
  • Subsetting - Basics • 4 minutes
  • Subsetting - Lists • 4 minutes
  • Subsetting - Matrices • 2 minutes
  • Subsetting - Partial Matching • 1 minute
  • Subsetting - Removing Missing Values • 3 minutes
  • Vectorized Operations • 3 minutes
  • Introduction to swirl • 1 minute

9 readings • Total 90 minutes

  • Welcome to R Programming • 10 minutes
  • About the Instructor • 10 minutes
  • Pre-Course Survey • 10 minutes
  • Syllabus • 10 minutes
  • Course Textbook • 10 minutes
  • Course Supplement: The Art of Data Science • 10 minutes
  • Data Science Podcast: Not So Standard Deviations • 10 minutes
  • Getting Started and R Nuts and Bolts • 10 minutes
  • Practical R Exercises in swirl Part 1 • 10 minutes

1 quiz • Total 30 minutes

  • Week 1 Quiz • 30 minutes

7 programming assignments • Total 1,260 minutes

  • swirl Lesson 1: Basic Building Blocks • 180 minutes
  • swirl Lesson 2: Workspace and Files • 180 minutes
  • swirl Lesson 3: Sequences of Numbers • 180 minutes
  • swirl Lesson 4: Vectors • 180 minutes
  • swirl Lesson 5: Missing Values • 180 minutes
  • swirl Lesson 6: Subsetting Vectors • 180 minutes
  • swirl Lesson 7: Matrices and Data Frames • 180 minutes

Week 2: Programming with R

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.

13 videos 3 readings 2 quizzes 3 programming assignments

13 videos • Total 90 minutes

  • Control Structures - Introduction • 0 minutes • Preview module
  • Control Structures - If-else • 1 minute
  • Control Structures - For loops • 4 minutes
  • Control Structures - While loops • 3 minutes
  • Control Structures - Repeat, Next, Break • 4 minutes
  • Your First R Function • 10 minutes
  • Functions (part 1) • 9 minutes
  • Functions (part 2) • 7 minutes
  • Scoping Rules - Symbol Binding • 10 minutes
  • Scoping Rules - R Scoping Rules • 8 minutes
  • Scoping Rules - Optimization Example (OPTIONAL) • 9 minutes
  • Coding Standards • 8 minutes
  • Dates and Times • 10 minutes

3 readings • Total 30 minutes

  • Week 2: Programming with R • 10 minutes
  • Practical R Exercises in swirl Part 2 • 10 minutes
  • Programming Assignment 1 INSTRUCTIONS: Air Pollution • 10 minutes

2 quizzes • Total 60 minutes

  • Week 2 Quiz • 30 minutes
  • Programming Assignment 1: Quiz • 30 minutes

3 programming assignments • Total 540 minutes

  • swirl Lesson 1: Logic • 180 minutes
  • swirl Lesson 2: Functions • 180 minutes
  • swirl Lesson 3: Dates and Times • 180 minutes

Week 3: Loop Functions and Debugging

We have now entered the third week of R Programming, which also marks the halfway point. The lectures this week cover loop functions and the debugging tools in R. These aspects of R make R useful for both interactive work and writing longer code, and so they are commonly used in practice.

8 videos 2 readings 1 quiz 2 programming assignments 1 peer review

8 videos • Total 61 minutes

  • Loop Functions - lapply • 9 minutes • Preview module
  • Loop Functions - apply • 7 minutes
  • Loop Functions - mapply • 4 minutes
  • Loop Functions - tapply • 3 minutes
  • Loop Functions - split • 9 minutes
  • Debugging Tools - Diagnosing the Problem • 12 minutes
  • Debugging Tools - Basic Tools • 6 minutes
  • Debugging Tools - Using the Tools • 8 minutes

2 readings • Total 20 minutes

  • Week 3: Loop Functions and Debugging • 10 minutes
  • Practical R Exercises in swirl Part 3 • 10 minutes
  • Week 3 Quiz • 30 minutes

2 programming assignments • Total 360 minutes

  • swirl Lesson 1: lapply and sapply • 180 minutes
  • swirl Lesson 2: vapply and tapply • 180 minutes

1 peer review • Total 60 minutes

  • Programming Assignment 2: Lexical Scoping • 60 minutes

Week 4: Simulation & Profiling

This week covers how to simulate data in R, which serves as the basis for doing simulation studies. We also cover the profiler in R which lets you collect detailed information on how your R functions are running and to identify bottlenecks that can be addressed. The profiler is a key tool in helping you optimize your programs. Finally, we cover the str function, which I personally believe is the most useful function in R.

6 videos 4 readings 2 quizzes 3 programming assignments

6 videos • Total 42 minutes

  • The str Function • 6 minutes • Preview module
  • Simulation - Generating Random Numbers • 7 minutes
  • Simulation - Simulating a Linear Model • 4 minutes
  • Simulation - Random Sampling • 2 minutes
  • R Profiler (part 1) • 10 minutes
  • R Profiler (part 2) • 10 minutes

4 readings • Total 40 minutes

  • Week 4: Simulation & Profiling • 10 minutes
  • Practical R Exercises in swirl Part 4 • 10 minutes
  • Programming Assignment 3 INSTRUCTIONS: Hospital Quality • 10 minutes
  • Post-Course Survey • 10 minutes
  • Week 4 Quiz • 30 minutes
  • Programming Assignment 3: Quiz • 30 minutes
  • swirl Lesson 1: Looking at Data • 180 minutes
  • swrl Lesson 2: Simulation • 180 minutes
  • swirl Lesson 3: Base Graphics • 180 minutes

coursera r programming assignment 2 lexical scoping

The mission of The Johns Hopkins University is to educate its students and cultivate their capacity for life-long learning, to foster independent and original research, and to bring the benefits of discovery to the world.

Why people choose Coursera for their career

coursera r programming assignment 2 lexical scoping

Learner reviews

Showing 3 of 22206

22,206 reviews

Reviewed on Aug 12, 2019

Very challenging, but good course. I've been programming in R for over a year, but there were still some things for me to pick up in this class. Assignments were a challenge, but satisfying to tackle.

Reviewed on Feb 21, 2017

I am pleasantly surprised with the quality of this course. For a beginner, the Swirl exercises are incredibly helpful and I was able to build confidence in working with R because of them. Thank you!

Reviewed on May 27, 2017

This was very engaging, however, the level of expectation and effort needed is much greater than course 1 - ToolBox.

This is perhaps the best course on R Programming designed for a small duration.

Placeholder

Open new doors with Coursera Plus

Unlimited access to 7,000+ world-class courses, hands-on projects, and job-ready certificate programs - all included in your subscription

Advance your career with an online degree

Earn a degree from world-class universities - 100% online

Join over 3,400 global companies that choose Coursera for Business

Upskill your employees to excel in the digital economy

coursera r programming assignment 2 lexical scoping

R Programming (JHU Coursera, Course 2)

Michael Galarnyk

Michael Galarnyk

Towards Data Science

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 difficulty was a bit too much for true beginners to R. In result, I decided to post all my code on my github .

I did this course with a bit of a twist. Instead of working purely with data.frames, I decided to use the highly popular data.table package instead of just relying on data.frame which isn’t as widely used as data.table for large datasets.

Week 1 Highlights: Removing and Subsetting Data is a highly useful skill. The teaching of vectors, lists, matrices, and factors was superb. Wasn’t too difficult.

Week 2 Highlights: Lexical scoping as the reason why all objects must be stored in memory. Programming assignment is useful. As seen below, I have decided to do as much of the specialization in data.table syntax as possible since it is widely used in industry.

Week 2 Horrors: Lots of users have complained about the considerable increase in difficulty for this weeks project. That is partly why I decided to put all my work on my github.

Week 3 Highlights: Opportunity to Practice my data.table skills (or lack thereof) on the quiz below. It is good to see the use of common datasets used as they are easy to manipulate. The assignment wasn’t too bad.

Week 4 Highlights: The quiz wasn’t bad. Lectures on R Profiler. There was a good note on optimization being a priority when the code is designed, working, and understandable. Figuring out best hospital by state by ordering, groupby etc was fun. The assignment was a bit much in my opinion considering it is a beginner specialization. The thumbnail image is what I generated in the early portion of this assignment.

Overall, this was a highly useful course for industry as it teaches people to take data files and manipulate them. It did however expect too much too fast for beginners. Please let me know if you have any questions by leaving a comment!

Also, please see my Course 3 Getting and Cleaning Data Review !

Michael Galarnyk

Written by Michael Galarnyk

Data Scientist https://www.linkedin.com/in/michaelgalarnyk/

Text to speech

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

Twitter Facebook Google+

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

Programming Assignment 2 Lexical Scoping Coursera Instructions

User Manual:

PDF

Navigation menu

  • Upload a User Manual

Versions of this User Manual:

  • Download & Help
  • User Manual
  • Discussion / Help
  • © 2024 UserManual.wiki

Data Visualization

  • Statistics in R
  • Machine Learning in R
  • Data Science in R

Packages in R

  • R Tutorial | Learn R Programming Language

Introduction

  • R Programming Language - Introduction
  • Interesting Facts about R Programming Language
  • R vs Python
  • Environments in R Programming
  • Introduction to R Studio
  • How to Install R and R Studio?
  • Creation and Execution of R File in R Studio
  • Clear the Console and the Environment in R Studio
  • Hello World in R Programming

Fundamentals of R

  • Basic Syntax in R Programming
  • Comments in R
  • R Operators
  • R - Keywords
  • R Data Types
  • R Variables - Creating, Naming and Using Variables in R
  • Scope of Variable in R
  • Dynamic Scoping in R Programming

Lexical Scoping in R Programming

Input/output.

  • Taking Input from User in R Programming
  • Printing Output of an R Program
  • Print the Argument to the Screen in R Programming - print() Function

Control Flow

  • Control Statements in R Programming
  • Decision Making in R Programming - if, if-else, if-else-if ladder, nested if-else, and switch
  • Switch case in R
  • For loop in R
  • R - while loop
  • R - Repeat loop
  • goto statement in R Programming
  • Break and Next statements in R
  • Functions in R Programming
  • Function Arguments in R Programming
  • Types of Functions in R Programming
  • Recursive Functions in R Programming
  • Conversion Functions in R Programming

Data Structures

  • Data Structures in R Programming
  • R - Matrices
  • R - Data Frames

Object Oriented Programming

  • R - Object Oriented Programming
  • Classes in R Programming
  • R - Objects
  • Encapsulation in R Programming
  • Polymorphism in R Programming
  • R - Inheritance
  • Abstraction in R Programming
  • Looping over Objects in R Programming
  • S3 class in R Programming
  • Explicit Coercion in R Programming

Error Handling

  • Handling Errors in R Programming
  • Condition Handling in R Programming
  • Debugging in R Programming

File Handling

  • File Handling in R Programming
  • Reading Files in R Programming
  • Writing to Files in R Programming
  • Working with Binary Files in R Programming
  • Packages in R Programming
  • Data visualization with R and ggplot2
  • dplyr Package in R Programming
  • Grid and Lattice Packages in R Programming
  • Shiny Package in R Programming
  • tidyr Package in R Programming
  • What Are the Tidyverse Packages in R Language?
  • Data Munging in R Programming

Data Interfaces

  • Data Handling in R Programming
  • Importing Data in R Script
  • Exporting Data from scripts in R Programming
  • Working with CSV files in R Programming
  • Working with XML Files in R Programming
  • Working with Excel Files in R Programming
  • Working with JSON Files in R Programming
  • Working with Databases in R Programming
  • Data Visualization in R
  • R - Line Graphs
  • R - Bar Charts
  • Histograms in R language
  • Scatter plots in R Language
  • R - Pie Charts
  • Boxplots in R Language
  • R - Statistics
  • Mean, Median and Mode in R Programming
  • Calculate the Average, Variance and Standard Deviation in R Programming
  • Descriptive Analysis in R Programming
  • Normal Distribution in R
  • Binomial Distribution in R Programming
  • ANOVA (Analysis of Variance) Test in R Programming
  • Covariance and Correlation in R Programming
  • Skewness and Kurtosis in R Programming
  • Hypothesis Testing in R Programming
  • Bootstrapping in R Programming
  • Time Series Analysis in R

Machine Learning

  • Introduction to Machine Learning in R
  • Setting up Environment for Machine Learning with R Programming
  • Supervised and Unsupervised Learning in R Programming
  • Regression and its Types in R Programming
  • Classification in R Programming
  • Naive Bayes Classifier in R Programming
  • KNN Classifier in R Programming
  • Clustering in R Programming
  • Decision Tree in R Programming
  • Random Forest Approach in R Programming
  • Hierarchical Clustering in R Programming
  • DBScan Clustering in R Programming
  • Deep Learning in R Programming

Lexical Scoping in R programming means that the values of the free variables are searched for in the environment in which the function was defined. An environment is a collection of symbols, value, and pair, every environment has a parent environment it is possible for an environment to have multiple children but the only environment without the parent is the empty environment. If the value of the symbol is not found in the environment in which the function was defined then the search is continued in the parent environment. In R, the free variable bindings are resolve by first looking in the environment in which the function was created. This is called Lexical Scoping .

Why Lexical Scoping?

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. Lexical scoping looks up to symbol based on how functions were nested initially when they were created and not on how they were nested when they called upon. When we use lexical scoping we don’t have to know how the function is called and to figure out where the value of the variable will be looked upon. We only have to look at the function’s definition.

Lexical meaning in lexical scoping is completely different from usual English definition which means relating to words or vocabulary of a language which is distinguished from grammar and construction rather it comes from computer science term lexing meaning by which process that converts code represented as text to meaningful pieces which is comprehensible by programming language. Consider the following example:

  • x and y are formal arguments
  • z as the free variable

Therefore, the scoping rules of the language determine how values are assigned to free variables. Free variables are not formal arguments and not local variables that are assigned inside of the function body.

Principles of Lexical Scoping

There are four basic principles behind R’s implementation of lexical scoping:

Name Masking

  • Functions vs variables
  • A fresh start

Dynamic Lookup

Let’s discuss each principle one by one.

The following example illustrates the most basic principle of lexical scoping, and you should have no problem predicting the output.

It takes the c value as 10 and then adds these numbers and finally we are having 23 as output.

Functions vs Variables

The same principles apply regardless of the type of associated value — finding functions works exactly the same way as finding variables: Example:

A Fresh Start

When a function is called, a new environment is created every time. Each acknowledgement is completely independent because a function cannot tell what happened when it was run last time. Example:

Lexical scoping controls where to look for values not when to look for them. R looks for the values when the function is executed not when it is created. The output of the function can be different depending on objects outside its environment. Example:

There is a function in R which is findGlobals() from codetools and it helps us to find all global variables being used in a function and lists all the external dependencies of a function. findGlobals() find the global variables and functions which are used by the closure. Example:

 

We can manually change the environment to the empty environment emptyenv() . emptyenv() is a totally empty environment.

author

Please Login to comment...

Similar reads.

  • R-Variables

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

Instantly share code, notes, and snippets.

@skeremaydin

skeremaydin / Week 3 programming assignment_b.r

  • Download ZIP
  • Star ( 0 ) 0 You must be signed in to star a gist
  • Fork ( 0 ) 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
  • Save skeremaydin/a7e32cf31a7f9249031120e6708ef073 to your computer and use it in GitHub Desktop.
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"
makeCacheMatrix <- function(x = matrix(sample(1:100,9),3,3)) {
s <- NULL
set <- function(y) {
x <<- y
s <<- NULL
}
get <- function() x
setsolve <- function(solve) s <<- solve
getsolve <- function() s
list(set = set, get = get,
setsolve = setsolve,
getsolve = getsolve)
}
##
## Same here, changed "mean" to "solve" and "m" to "s"
cacheSolve <- function(x, ...) {
s <- x$getsolve()
if(!is.null(s)) {
message("getting inversed matrix")
return(s)
}
data <- x$get()
s <- solve(data, ...)
x$setsolve(s)
s
}

IMAGES

  1. Programming Assignment 2 Lexical Scoping Coursera Instructions

    coursera r programming assignment 2 lexical scoping

  2. Programming Assignment 2 Lexical Scoping Coursera Instructions

    coursera r programming assignment 2 lexical scoping

  3. GitHub

    coursera r programming assignment 2 lexical scoping

  4. GitHub

    coursera r programming assignment 2 lexical scoping

  5. Programming Assignment 2 Lexical Scoping Coursera Instructions

    coursera r programming assignment 2 lexical scoping

  6. GitHub

    coursera r programming assignment 2 lexical scoping

VIDEO

  1. R Programming Language Tutorial & Complete Data Science Roadmap

  2. FISH DETECION USING Faster R-CNN Object Detection #PYTHON CODE

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

  4. ggplot2 part 1 Johns Hopkins University Coursera

  5. Reading JSON Johns Hopkins University Coursera

  6. Reading Local Files Johns Hopkins University Coursera

COMMENTS

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

    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. Repository for Programming Assignment 2 for R Programming on Coursera

    In this Programming Assignment you 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

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

    R Programming Week 3 Programming Assignments 2: Lexical Scoping StanLee ... 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 ...

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

    2 Answers. Sorted by: 3. x <<- y creates x, which is then retrieved by get (). Note that get is also a base function and is being overwritten here. I would advocate in avoiding this, even though it's confined to a function. An ad hoc solution would be to reach base get function through base::get. Line get <- function () x is a "short" version ...

  5. benislam/Assignment-2-Lexical-Scoping

    Peer-graded Assignment: Programming Assignment 2: Lexical Scoping. InstructionsMy submissionDiscussions This programming assignment is required 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.

  6. Coursera course "R Programming"

    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.

  7. R Programming Assignment 2: Lexical Scoping

    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 ...

  8. PDF Peer-graded Assignment: Programming Assignment 2: Lexical Scoping

    Back to Week 3 Lessons This Course : R Programming Prev Next less less Discussions Peer-graded Assignment: Programming Assignment 2: Lexical Scoping You passed! Congratulations. You earned 12 / 12 points. Instructions My submission second programming assignment will require you to write an R function is able to cache potentially time-consuming ...

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

    Download ZIP. Peer-graded Assignment: Programming Assignment 2: Lexical Scoping. Raw. Week 3 R assignment. 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. Learn more about bidirectional Unicode ...

  10. R Programming Course by Johns Hopkins University

    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. ... Programming Assignment 2: Lexical Scoping ... Coursera is one of the best places to go." Chaitanya A. "Learning isn't just about being better at your job: it's so much more than that. Coursera ...

  11. R Programming

    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. ... Programming Assignment 2: Lexical Scoping ... Coursera is one of the best places to go." Chaitanya A. "Learning isn't just about being better at your job: it's so much more than that. Coursera ...

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

    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.

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

    Sign inRegister. R Programming Week 3 Programming Assignments 2: Lexical Scoping. by Louis Stanley. Last updatedover 1 year ago. HideComments(-)ShareHide Toolbars. ×. Post on: TwitterFacebookGoogle+. Or copy & paste this link into an email or IM:

  14. R Programming (JHU Coursera, Course 2)

    R Programming JHU Quiz 1. Week 2 Highlights: Lexical scoping as the reason why all objects must be stored in memory. Programming assignment is useful. As seen below, I have decided to do as much of the specialization in data.table syntax as possible since it is widely used in industry.

  15. RPubs

    R Pubs by RStudio. Sign in Register Programming Assignment 2: Lexical Scoping JHU; by [email protected]; Last updated almost 4 years ago; Hide Comments (-) Share Hide Toolbars

  16. GitHub

    Repository for Programming Assignment 2 for R Programming on Coursera - wuj186/Lexical-Scoping. Skip to content. Navigation Menu Toggle navigation. Sign in Product Actions. Automate any workflow Packages. Host and manage packages Security. Find and fix vulnerabilities Codespaces ...

  17. josecarlosgt/R_Programming_Lexical_Scoping

    Repository for Programming Assignment 2 for R Programming on Coursera - josecarlosgt/R_Programming_Lexical_Scoping

  18. Programming Assignment 2 Lexical Scoping Coursera Instructions

    second programming assignment will require you to write an R function is able to cache

  19. Lexical Scoping in R Programming

    Lexical Scoping in R programming means that the values of the free variables are searched for in the environment in which the function was defined. An environment is a collection of symbols, value, and pair, every environment has a parent environment it is possible for an environment to have multiple children but the only environment without the parent is the empty environment.

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

    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.

  21. I need urgent help with peer reviews. : r/coursera

    I need urgent help with peer reviews. My deadline for completing the R Programming course on Coursera from Johns Hopkins University is in a few hours. The only thing remaining for me to complete the course is that I need my assignment to be peer-reviewed. If you decide to help, enrol in the free trial for the course on Coursera, and go here ...