- Coursera R programming week 4 assignment 3
- by Haolei Fang
- Last updated almost 7 years ago
- Hide Comments (–) Share Hide Toolbars
Twitter Facebook Google+

Or copy & paste this link into an email or IM:
Instantly share code, notes, and snippets.
mGalarnyk / assignment3.md
R programming project 3.
github repo for rest of specialization: Data Science Coursera
The zip file containing the data can be downloaded here: Assignment 3 Data
Part 1 Plot the 30-day mortality rates for heart attack ( outcome.R )

Part 2 Finding the best hospital in a state ( best.R )
Part 3 ranking hospitals by outcome in a state ( rankhospital.r ), part 4 ranking hospitals in all states ( rankall.r ).
aditya-rane1 commented Jul 6, 2020
I share the same feeling! The course is poorly designed with link between assignment and course material being so wide. This sometimes creates frustration of quitting the course. This made me think whether this course was designed to learn R or make money. By the way Thank you for your solution!
Sorry, something went wrong.
vickkiee commented Jul 7, 2020
Thank you for your solution
sereivatananath commented Jul 15, 2020 • edited
The course isn't for the student's learning ability but for student's cheating ability. This course didn't teach me or explain me to find the solution to solve the assignment; in contrast, it encouraged me to google and copy other's code. I am feeling that I am in the wrong course. I am about to quit. I have no idea why JHU and instructor created irresponsible course like this.
sushilsushil commented Jul 18, 2020
Yo everyone feels the same way. I didn't like the constant saliva sound of that guy. Very poor course design too.
BouNaj commented Jul 25, 2020
I share the same feeling. I was frustrated the content does in no way prepare you to do anything of the sort the assignments require.
Chiagozie-Umeano commented Aug 4, 2020
I thought I was the only one having this difficulty in writing code and functions. Was feeling bad for choosing this course, we are not properly taught how to write these codes. I have being feeling to quit the course..
abduljan71 commented Aug 7, 2020
Hey, I am with it. I am doing the same. The course itself does not help you that much for you to understand and do your own coding. I feel very bad.
shaunkok64 commented Aug 16, 2020 • edited
Thank you for your solution. I am glad that there are so many people feeling the same. As I don't have any knowledge regarding coding in general and I wanted to take this course to learn something new such as Data Science. This course could be great if designed properly but the course is not that learner friendly, in some cases even people with experience with coding may not able to cope it and this has led me thoughts to quit. This course are expecting learners to do their own coding without giving guidance to learners. WHY! There are so little guidance given to readers until I had to Google Search for answers. I need to take sometime to study it after I have passed this.
Gareeeb7 commented Aug 27, 2020
Utha re ba ba uthle Coursera ko
Thanks for your Solution
Fahad-98 commented Aug 30, 2020
How do I submit my assignment.
SaneClouxz commented Sep 14, 2020
How do I submit my assignment. It's a multi choice quiz which you'll solve using the functions provided in this solution.
nfabregas commented Sep 25, 2020
Same here. The problem is simple: the course don't give you the tools and knowledge that someone with no experience with code needs to do the Assignments. It looks like assignments are from another course.
100% agree with D-Se:
Coursera lecture: "The drivetrain of a car looks like this" Swirl: "A car can move hurr durrr" Assignment: "build a car and test it, or else fail the course"
anikvh commented Sep 25, 2020
I agree with the comments above, there is a huge gap between the lectures and the assingments. Thank you so much for sharing this!
Songsuperjing commented Sep 27, 2020
love the above comments. so true.
Arnab-eco commented Oct 8, 2020 • edited
I totally agree with the comments. Unfortunately, The instructor thinks that everyone is a master level programmer. His presentations lack the necessary insight. His assignments are way over the mark. I understand that if someone can complete these assignments, they can learn a lot. But frankly, it's like asking someone to write a novel after teaching them how to read. The swirl exercises do teach the basics, but is absolutely hopeless as it doesn't even allow us to make the smallest changes to a code.
benthecoder commented Oct 18, 2020 • edited
I'm glad many are learning this specialization even today, I was hoping if anyone can direct me to any discord servers or like reddit groups to talk about the assignments, for discussions and to learn from each other. Thanks! And yea the assignments are crazy hard, but to be fair the coursera courses can't fit everything into their videos, so i believe it's encouraged to find ways to create a solution for yourself with the abundance of resources online.
is this part wrong? return(dt[order(state, get(outcome), hospital name ) , head(.SD, num) , by = state , .SDcols = c("hospital name")])
I can't seem to get the right answers with this part. Anyone has a revision of this part of the code?
siyangni commented Nov 26, 2020 • edited
This course is just designed to make me feel bad. I was in the honor's college while I was a senior, now I am getting my master in sociology. Throughout my academic career so far I've never Googled anyone else's assignment. And this course makes me do this for every assignment!!!!!! By the way, I have a decent knowledge of programming where I gain from learning Python. I thought this class would be easy for me (after quickly going through the lecture videos), yet from the first assignment I began to scratch my head for an answer.
Guess what? the following courses for this specialization are just no better. At first sight I thought the instructors may have problems with their pedagogy. After going through several courses of JHU's Data Science Specialization, I highly doubt it's not just pedagogy, it is their attitude. There is no way the three instructors who should be incredibly smart people cannot find the embarrassingly obvious large gap between the course material and the assignments/quizzes in every one of their courses. And they rush through every course in this specialization. I paid for those courses though! I really want to file a complaint on Coursera.
amingraphy commented Nov 28, 2020
I agree the course it useless. Instead I started learning by reading a time-consuming textbook, called "discovering statistics using R". I even think the material provided by Roger Peng are not all in the same basic level. He doesn't teach basic tools of R, but then he jumps to using multi-core computation on your computer to speed up the calculation! It is just ridiculous
DanEscasa commented Dec 30, 2020 • edited
Thanks for the hard work. I chose not to shorten the unwieldingly long column names, just used switch :
outcome <- switch(outcome, "heart attack" = "Hospital.30.Day.Death..Mortality..Rates.from.Heart.Attack", "heart failure" = "Hospital.30.Day.Death..Mortality..Rates.from.Heart.Failure", "pneumonia" = "Hospital.30.Day.Death..Mortality..Rates.from.Pneumonia", NULL) if (is.null(outcome)) { stop(" : invalid outcome") }
<rant> Isn't there a way to preserve the indentation in a code block? </rant>
As to Roger Peng's teaching, I was looking for a functional programming-oriented approach. He still treats it like a procedural language. I should write up something on that in codementor.io
charlenelch13 commented Jan 3, 2021
Thank you so much for the sharing!! It is sooo helpful! I had zero knowledge about programming before taking this course. I feel frustrated about learning the logics from the course materials. They are so vague and not supported by daily examples. I don't know how they can assume students to know how to finish the assignments... Thank you for guiding me!!
EmilieWaite18 commented Mar 23, 2021
I have never been so frustrated by anything. I have had to look up every single answer to these assignments.
anaidcandido commented Jun 1, 2021
Many thanks for sharing!! I also thought I was the only one struggling with the course but I'm "glad" to see is the course itself. Now I am able to analyze and compare what I was doing. Thanks a lot!
yeho-bt commented Jun 13, 2021
Hmmmm, I am not alone feeling like this.
jdpm93 commented Oct 5, 2021
I have the same problem, the gap between the lessons, swirl, and the assigments is horrible and frustrating. some excercises require the use of things never covered in the videos or swirl, I see that many have sent feedback but they are not taking action on this, also the video lessons need to be updated it's 2021 and the videos were recorded in 2015. this is insane. Thank you for sharing.
codobene commented Dec 16, 2021
truth is, the world is not meant for everyone to be kept alive - it just needs the upper 10% of people that manage this course well. Same is true for jobs in general, stock market, etc etc get it quickly, or work overtime to compensate for your idiocy, or become social darvinism's fish food.
i blindly copy code that I find here, fail to reproduce anything, and take drugs. good night. good luck!
Juanvelz commented Mar 24, 2022
These people should learn how to teach before offering a course. On the other hand, they know very well how to discourage students.
emakello commented Mar 27, 2022
The essence of taking an online course is to learn skills that can help you in your career or academics. While the courses are stimulating, it makes no sense to bring assignments that discourage rather than encourage learners. Some people like me had never coded before and I spend hours trying to do this thing without success. I wish there was someone who could teach coding from scratch without assuming any prior knowledge.

cfsobral commented Jan 22, 2023
Thank you for help. I believe that the course already expects us to look for solutions like this one from mGalarnyk, otherwise it would not make sense to pass on an assignment of this complexity for beginners to do, because many like me would get frustrated and give up the course, as I read in some comments made here. Thank you mGalarnyk
Famous Dojo
Work Harder.

R Programming Week 4 Programming Assignment 3: Hospital Quality
My solution after referring to online sources:
1. Plot the 30-day mortality rates for heart attack
> outcome <- read.csv(“outcome-of-care-measures.csv”, colClasses = “character”)
> head(outcome)
> outcome[, 11] <- as.numeric(outcome[, 11])
## You may get a warning about NAs being introduced; that is okay
> hist(outcome[, 11])
2. Finding the best hospital in a state
best <- function(state, outcome) { ## Read outcome data data <- read.csv(“outcome-of-care-measures.csv”)
for(i in 1:length(states)){ if(state == states[i]){ state_name <- TRUE } } if(state_name == FALSE){ stop(“invalid state”) }
if (!((outcome == “heart attack”) | (outcome == “heart failure”) | (outcome == “pneumonia”))) { stop (“invalid outcome”) }
3. Ranking hospitals by outcome in a state
rankhospital <- function(state, outcome,num) { ## Read outcome data data <- read.csv(“outcome-of-care-measures.csv”)
4. Ranking hospitals in all states
rankall <- function(outcome, num = “best”) { ## Read outcome data data <- read.csv(“outcome-of-care-measures.csv”)
output <- vector()
Share this:
Leave a reply cancel reply.
Fill in your details below or click an icon to log in:
You are commenting using your WordPress.com account. ( Log Out / Change )
You are commenting using your Twitter account. ( Log Out / Change )
You are commenting using your Facebook account. ( Log Out / Change )
Connecting to %s
Notify me of new comments via email.
Notify me of new posts via email.

- Already have a WordPress.com account? Log in now.
- Follow Following
- Copy shortlink
- Report this content
- View post in Reader
- Manage subscriptions
- Collapse this bar
Programming Assignment 3: Hospital Quality
My code repository for coursera data science specialization by john hopkins university, assignment instructions.
The data for this assignment come from the Hospital Compare web site (http://hospitalcompare.hhs.gov) run by the U.S. Department of Health and Human Services. The purpose of the web site is to provide data and information about the quality of care at over 4,000 Medicare-certified hospitals in the U.S. This dataset es- sentially covers all major U.S. hospitals. This dataset is used for a variety of purposes, including determining whether hospitals should be fined for not providing high quality care to patients (see http://goo.gl/jAXFX for some background on this particular topic).
The Hospital Compare web site contains a lot of data and we will only look at a small subset for this assignment. The zip file for this assignment contains three files
- outcome-of-care-measures.csv: Contains information about 30-day mortality and readmission rates for heart attacks, heart failure, and pneumonia for over 4,000 hospitals.
- hospital-data.csv: Contains information about each hospital.
- Hospital_Revised_Flatfiles.pdf: Descriptions of the variables in each file (i.e the code book).
A description of the variables in each of the files is in the included PDF file named Hospital_Revised_Flatfiles.pdf. This document contains information about many other files that are not included with this programming assignment. You will want to focus on the variables for Number 19 (“Outcome of Care Measures.csv”) and Number 11 (“Hospital Data.csv”). You may find it useful to print out this document (at least the pages for Tables 19 and 11) to have next to you while you work on this assignment. In particular, the numbers of the variables for each table indicate column indices in each table (i.e. “Hospital Name” is column 2 in the outcome-of-care-measures.csv file)
More information about the assignment here
Data zip file - link
1 Plot the 30-day mortality rates for heart attack - outcome.R

2 Finding the best hospital in a state - best.R
Write a function called best that take two arguments: the 2-character abbreviated name of a state and an outcome name. The function reads the outcome-of-care-measures.csv file and returns a character vector with the name of the hospital that has the best (i.e. lowest) 30-day mortality for the specified outcome in that state. The hospital name is the name provided in the Hospital.Name variable. The outcomes can be one of “heart attack”, “heart failure”, or “pneumonia”. Hospitals that do not have data on a particular outcome should be excluded from the set of hospitals when deciding the rankings.
3 Ranking hospitals by outcome in a state - rankhospital.R
Write a function called rankhospital that takes three arguments: the 2-character abbreviated name of a state (state), an outcome (outcome), and the ranking of a hospital in that state for that outcome (num). The function reads the outcome-of-care-measures.csv file and returns a character vector with the name of the hospital that has the ranking specified by the num argument. For example, the call rankhospital(“MD”, “heart failure”, 5) would return a character vector containing the name of the hospital with the 5th lowest 30-day death rate for heart failure. The num argument can take values “best”, “worst”, or an integer indicating the ranking (smaller numbers are better). If the number given by num is larger than the number of hospitals in that state, then the function should return NA. Hospitals that do not have data on a particular outcome should be excluded from the set of hospitals when deciding the rankings.
4 Ranking hospitals in all states - rankall.R
Write a function called rankall that takes two arguments: an outcome name (outcome) and a hospital ranking (num). The function reads the outcome-of-care-measures.csv file and returns a 2-column data frame containing the hospital in each state that has the ranking specified in num. For example the function call rankall(“heart attack”, “best”) would return a data frame containing the names of the hospitals that are the best in their respective states for 30-day heart attack death rates. The function should return a value for every state (some may be NA). The first column in the data frame is named hospital, which contains the hospital name, and the second column is named state, which contains the 2-character abbreviation for the state name. Hospitals that do not have data on a particular outcome should be excluded from the set of hospitals when deciding the rankings.
- Online Degree Explore Bachelor’s & Master’s degrees
- MasterTrack™ Earn credit towards a Master’s degree
- University Certificates Advance your career with graduate-level learning
- Top Courses
- Join for Free
- R Programming
- Thumbs Up 94%

Financial aid available
About 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.
Familiarity with regression is recommended.
Could your company benefit from training employees on in-demand skills?
What you will 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
Skills you will gain
- Data Analysis
Instructors

Roger D. Peng, PhD

Jeff Leek, PhD

Brian Caffo, PhD

Johns Hopkins University
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.
See how employees at top companies are mastering in-demand skills
Syllabus - What you will learn from this course
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.
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.
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.
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.
- 5 stars 68.11%
- 4 stars 22.14%
- 3 stars 5.83%
- 2 stars 2.06%
- 1 star 1.83%
TOP REVIEWS FROM R PROGRAMMING
Really interesting course. The interactive coding sessions with swirl are especially useful. Would be great, if you provided sample solutions for the programming assignments, in particular for week 4.
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.
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.
The content is superbly designer for a beginner. The Swirl assignments need to make compulsory. Infact they contributed more to the learning process. More Swirl contents will make the course richer.
Frequently Asked Questions
When will I have access to the lectures and assignments?
Access to lectures and assignments depends on your type of enrollment. If you take a course in audit mode, you will be able to see most course materials for free. To access graded assignments and to earn a Certificate, you will need to purchase the Certificate experience, during or after your audit. If you don't see the audit option:
The course may not offer an audit option. You can try a Free Trial instead, or apply for Financial Aid.
The course may offer 'Full Course, No Certificate' instead. This option lets you see all course materials, submit required assessments, and get a final grade. This also means that you will not be able to purchase a Certificate experience.
What will I get if I subscribe to this Specialization?
When you enroll in the course, you get access to all of the courses in the Specialization, and you earn a certificate when you complete the work. Your electronic Certificate will be added to your Accomplishments page - from there, you can print your Certificate or add it to your LinkedIn profile. If you only want to read and view the course content, you can audit the course for free.
Is financial aid available?
Yes. In select learning programs, you can apply for financial aid or a scholarship if you can’t afford the enrollment fee. If fin aid or scholarship is available for your learning program selection, you’ll find a link to apply on the description page.
More questions? Visit the Learner Help Center .
Build employee skills, drive business results
Coursera Footer
Start or advance your career.
- Google Data Analyst
- Google Digital Marketing & E-commerce Professional Certificate
- Google IT Automation with Python Professional Certificate
- Google IT Support
- Google Project Management
- Google UX Design
- Preparing for Google Cloud Certification: Cloud Architect
- IBM Cybersecurity Analyst
- IBM Data Analyst
- IBM Data Engineering
- IBM Data Science
- IBM Full Stack Cloud Developer
- IBM Machine Learning
- Intuit Bookkeeping
- Meta Front-End Developer
- DeepLearning.AI TensorFlow Developer Professional Certificate
- SAS Programmer Professional Certificate
- Launch your career
- Prepare for a certification
- Advance your career
- How to Identify Python Syntax Errors
- How to Catch Python Exceptions
- See all Programming Tutorials
Popular Courses and Certifications
- Free Courses
- Artificial Intelligence Courses
- Blockchain Courses
- Computer Science Courses
- Cursos Gratis
- Cybersecurity Courses
- Data Analysis Courses
- Data Science Courses
- English Speaking Courses
- Full Stack Web Development Courses
- Google Courses
- Human Resources Courses
- Learning English Courses
- Microsoft Excel Courses
- Product Management Courses
- Project Management Courses
- Python Courses
- SQL Courses
- Agile Certifications
- CAPM Certification
- CompTIA A+ Certification
- Data Analytics Certifications
- Scrum Master Certifications
- See all courses
Popular collections and articles
- Free online courses you can finish in a day
- Popular Free Courses
- Business Jobs
- Cybersecurity Jobs
- Entry-Level IT Jobs
- Data Analyst Interview Questions
- Data Analytics Projects
- How to Become a Data Analyst
- How to Become a Project Manager
- Project Manager Interview Questions
- Python Programming Skills
- Strength and Weakness in Interview
- What Does a Data Analyst Do
- What Does a Software Engineer Do
- What Is a Data Engineer
- What Is a Data Scientist
- What Is a Product Designer
- What Is a Scrum Master
- What Is a UX Researcher
- How to Get a PMP Certification
- PMI Certifications
- Popular Cybersecurity Certifications
- Popular SQL Certifications
- Read all Coursera Articles
Earn a degree or certificate online
- Google Professional Certificates
- Professional Certificates
- See all certificates
- Bachelor's Degrees
- Master's Degrees
- Computer Science Degrees
- Data Science Degrees
- MBA & Business Degrees
- Data Analytics Degrees
- Public Health Degrees
- Social Sciences Degrees
- Management Degrees
- BA vs BS Degree
- What is a Bachelor's Degree?
- 11 Good Study Habits to Develop
- How to Write a Letter of Recommendation
- 10 In-Demand Jobs You Can Get with a Business Degree
- Is a Master's in Computer Science Worth it?
- See all degree programs
- Coursera India
- Coursera UK
- Coursera Mexico
- What We Offer
- Coursera Plus
- MasterTrack® Certificates
- For Enterprise
- For Government
- Become a Partner
- Coronavirus Response
- Beta Testers
- Translators
- Teaching Center
- Accessibility
- Modern Slavery Statement


Towards Data Science

Dec 27, 2016
R Programming (JHU Coursera, Course 2)
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 !
More from Towards Data Science
Your home for data science. A Medium publication sharing concepts, ideas and codes.
About Help Terms Privacy
Get the Medium app

Michael Galarnyk
Data Scientist https://www.linkedin.com/in/michaelgalarnyk/
Text to speech

IMAGES
VIDEO
COMMENTS
Course 2 R Programming, Assignment 3 (Week 4), under Data Science by Johns Hopkins University. 1 Plot the 30-day mortality rates for heart
Coursera R Week 4 programming assignment 3. Mike Fang. March 13, 2016. I'd say this is a tougher project than I thought it was
R Programming Programming Assignment 3 (Week 4) John Hopkins Data Science Specialization Coursera for the github repo
R Programming Week 4 Programming Assignment 3: Hospital Quality · 1. Plot the 30-day mortality rates for heart attack. > outcome <- read. · 2.
4 Ranking hospitals in all states - rankall.R. Write a function called rankall that takes two arguments: an outcome name (outcome) and a hospital ranking (num).
course link: https://www.coursera.org/learn/r-programming?Friends support me to give you more useful videos.Subscribe me and comment me
In this course you will learn how to program in R and how to use R for effective ... solutions for the programming assignments, in particular for week 4.
Course Content Week 1: Overview of R, R data types and objects, ... and times Week 3: Loop functions, debugging tools Week 4: Simulation, code profiling.
Histogram Showing Mortality Rates (Part of Week 4 Assignment). The second course in the data science specialization, “R Programming” is an introductory
View R Programming Programming Assignment Week 3.pdf from CSC 103 at University of Ibadan.