SlideShare a Scribd company logo
Concept Mapping
Patient initials, age, gender and admitting diagnosis
Nursing diagnosis
Related to
As Evidence by
Nursing diagnosis
Related to
As Evidence by
Outcomes
Assessment
Signs / Symptoms
Subjective / Objective
Outcomes
Assessment
Signs / Symptoms
Subjective / Objective
Interventions
Interventions
Evaluation of Interventions / Outcomes
Medication
Dose, Route & Frequency
Classification
Purpose / Mechanism of Action
Significant Side Effects / Adverse Reactions
Nursing Implications
Concept mapping patient initials, age, gender and admitting d
Pathophysiological Discussion
1. APA format (citations and references)
2. Discuss the disease process: etiology, epidemiology, and
pathophysiologic mechanism
3. Identify common complications that may occur with the
alterations or treatment modalities
4. Patient’s overall prognosis
Data Visualization with R
Rob Kabacoff
2018-09-03
2
Contents
Welcome 7
Preface 9
How to use this book . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . 9
Prequisites . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . 10
Setup . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . 10
1 Data Preparation 11
1.1 Importing data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . 11
1.2 Cleaning data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . 12
2 Introduction to ggplot2 19
2.1 A worked example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . 19
2.2 Placing the data and mapping options . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . 30
2.3 Graphs as objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . 32
3 Univariate Graphs 35
3.1 Categorical . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . 35
3.2 Quantitative . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . 51
4 Bivariate Graphs 63
4.1 Categorical vs. Categorical . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . 63
4.2 Quantitative vs. Quantitative . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . 71
4.3 Categorical vs. Quantitative . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . 79
5 Multivariate Graphs 103
5.1 Grouping . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . 103
6 Maps 115
6.1 Dot density maps . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . 115
6.2 Choropleth maps . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . 119
3
4 CONTENTS
7 Time-dependent graphs 127
7.1 Time series . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . 127
7.2 Dummbbell charts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . 130
7.3 Slope graphs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . 133
7.4 Area Charts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . 135
8 Statistical Models 139
8.1 Correlation plots . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . 139
8.2 Linear Regression . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . 141
8.3 Logistic regression . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . 145
8.4 Survival plots . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . 147
8.5 Mosaic plots . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . 150
9 Other Graphs 153
9.1 3-D Scatterplot . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . 153
9.2 Biplots . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . 159
9.3 Bubble charts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . 161
9.4 Flow diagrams . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . 163
9.5 Heatmaps . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . 168
9.6 Radar charts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . 174
9.7 Scatterplot matrix . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . 176
9.8 Waterfall charts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . 178
9.9 Word clouds . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . 180
10 Customizing Graphs 183
10.1 Axes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . 183
10.2 Colors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . 187
10.3 Points & Lines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . 193
10.4 Legends . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . 195
10.5 Labels . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . 197
10.6 Annotations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . 199
10.7 Themes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . 206
11 Saving Graphs 219
11.1 Via menus . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . 219
11.2 Via code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . 219
11.3 File formats . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . 219
11.4 External editing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . 221
CONTENTS 5
12 Interactive Graphs 223
12.1 leaflet . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . 223
12.2 plotly . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . 223
12.3 rbokeh . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . 226
12.4 rCharts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . 226
12.5 highcharter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . 226
13 Advice / Best Practices 231
13.1 Labeling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . 231
13.2 Signal to noise ratio . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . 232
13.3 Color choice . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . 234
13.4 y-Axis scaling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . 234
13.5 Attribution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . 238
13.6 Going further . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . 238
13.7 Final Note . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . 239
A Datasets 241
A.1 Academic salaries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . 241
A.2 Starwars . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . 241
A.3 Mammal sleep . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . 241
A.4 Marriage records . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . 242
A.5 Fuel economy data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . 242
A.6 Gapminder data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . 242
A.7 Current Population Survey (1985) . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . 242
A.8 Houston crime data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . 242
A.9 US economic timeseries . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . 243
A.10 Saratoga housing data . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . 243
A.11 US population by age and year . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . 243
A.12 NCCTG lung cancer data . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . 243
A.13 Titanic data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . 243
A.14 JFK Cuban Missle speech . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . 244
A.15 UK Energy forecast data . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . 244
A.16 US Mexican American Population . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . 244
B About the Author 245
C About the QAC 247
6 CONTENTS
Welcome
R is an amazing platform for data analysis, capable of creating
almost any type of graph. This book helps
you create the most popular visualizations - from quick and
dirty plots to publication-ready graphs. The
text relies heavily on the ggplot2 package for graphics, but
other approaches are covered as well.
This work is licensed under a Creative Commons Attribution-
NonCommercial-NoDerivatives 4.0 Interna-
tional License.
My goal is make this book as helpful and user-friendly as
possible. Any feedback is both welcome and
appreciated.
7
8 CONTENTS
Preface
How to use this book
You don’t need to read this book from start to finish in order to
start building effective graphs. Feel free to
jump to the section that you need and then explore others that
you find interesting.
Graphs are organized by
• the number of variables to be plotted
• the type of variables to be plotted
• the purpose of the visualization
Chapter Description
Ch 1 provides a quick overview of how to get your data into R
and how to prepare it
for analysis.
Ch 2 provides an overview of the ggplot2 package.
Ch 3 describes graphs for visualizing the distribution of a single
categorical (e.g. race)
or quantitative (e.g. income) variable.
Ch 4 describes graphs that display the relationship between two
variables.
Ch 5 describes graphs that display the relationships among 3 or
more variables. It is
helpful to read chapters 3 and 4 before this chapter.
Ch 6 provides a brief introduction to displaying data
geographically.
Ch 7 describes graphs that display change over time.
Ch 8 describes graphs that can help you interpret the results of
statistical models.
Ch 9 covers graphs that do not fit neatly elsewhere (every book
needs a miscellaneous
chapter).
Ch 10 describes how to customize the look and feel of your
graphs. If you are going to
share your graphs with others, be sure to skim this chapter.
Ch 11 covers how to save your graphs. Different formats are
optimized for different
purposes.
Ch 12 provides an introduction to interactive graphics.
Ch 13 gives advice on creating effective graphs and where to go
to learn more. It’s
worth a look.
The Appendices describe each of the datasets used in this book,
and provides a short blurb about
the author and the Wesleyan Quantitative Analysis Center.
There is no one right graph for displaying data. Check out the
examples, and see which type best fits
your needs.
9
10 CONTENTS
Prequisites
It’s assumed that you have some experience with the R language
and that you have already installed R and
RStudio. If not, here are some resources for getting started:
• A (very) short introduction to R
• DataCamp - Introduction to R with Jonathon Cornelissen
• Quick-R
• Getting up to speed with R
Setup
In order to create the graphs in this guide, you’ll need to install
some optional R packages. To install all of
the necessary packages, run the following code in the RStudio
console window.
pkgs <- c("ggplot2", "dplyr", "tidyr",
"mosaicData", "carData",
"VIM", "scales", "treemapify",
"gapminder", "ggmap", "choroplethr",
"choroplethrMaps", "CGPfunctions",
"ggcorrplot", "visreg",
"gcookbook", "forcats",
"survival", "survminer",
"ggalluvial", "ggridges",
"GGally", "superheat",
"waterfalls", "factoextra",
"networkD3", "ggthemes",
"hrbrthemes", "ggpol",
"ggbeeswarm")
install.packages(pkgs)
Alternatively, you can install a given package the first time it is
needed.
For example, if you execute
library(gapminder)
and get the message
Error in library(gapminder) : there is no package called
‘gapminder’
you know that the package has never been installed. Simply
execute
install.packages("gapminder")
once and
library(gapminder)
will work from that point on.
https://cran.r-project.org/
https://www.rstudio.com/products/RStudio/#Desktop
https://cran.r-project.org/doc/contrib/Torfs+Brauer-Short-R-
Intro.pdf
https://www.datacamp.com/courses/free-introduction-to-r
http://www.statmethods.net
Chapter 1
Data Preparation
Before you can visualize your data, you have to get it into R.
This involves importing the data from an
external source and massaging it into a useful format.
1.1 Importing data
R can import data from almost any source, including text files,
excel spreadsheets, statistical packages, and
database management systems. We’ll illustrate these techniques
using the Salaries dataset, containing the 9
month academic salaries of college professors at a single
institution in 2008-2009.
1.1.1 Text files
The readr package provides functions for importing delimited
text files into R data frames.
library(readr)
# import data from a comma delimited file
Salaries <- read_csv("salaries.csv")
# import data from a tab delimited file
Salaries <- read_tsv("salaries.txt")
These function assume that the first line of data contains the
variable names, values are separated by commas
or tabs respectively, and that missing data are represented by
blanks. For example, the first few lines of the
comma delimited file looks like this.
"rank","discipline","yrs.since.phd","yrs.service","sex","salary"
"Prof","B",19,18,"Male",139750
"Prof","B",20,16,"Male",173200
"AsstProf","B",4,3,"Male",79750
"Prof","B",45,39,"Male",115000
"Prof","B",40,41,"Male",141500
"AssocProf","B",6,6,"Male",97000
Options allow you to alter these assumptions. See the
documentation for more details.
11
https://www.rdocumentation.org/packages/readr/versions/0.1.1/t
opics/read_delim
12 CHAPTER 1. DATA PREPARATION
1.1.2 Excel spreadsheets
The readxl package can import data from Excel workbooks.
Both xls and xlsx formats are supported.
library(readxl)
# import data from an Excel workbook
Salaries <- read_excel("salaries.xlsx", sheet=1)
Since workbooks can have more than one worksheet, you can
specify the one you want with the sheet option.
The default is sheet=1.
1.1.3 Statistical packages
The haven package provides functions for importing data from a
variety of statistical packages.
library(haven)
# import data from Stata
Salaries <- read_dta("salaries.dta")
# import data from SPSS
Salaries <- read_sav("salaries.sav")
# import data from SAS
Salaries <- read_sas("salaries.sas7bdat")
1.1.4 Databases
Importing data from a database requires additional steps and is
beyond the scope of this book. Depending on
the database containing the data, the following packages can
help: RODBC, RMySQL, ROracle, RPostgreSQL,
RSQLite, and RMongo. In the newest versions of RStudio, you
can use the Connections pane to quickly access
the data stored in database management systems.
1.2 Cleaning data
The processes of cleaning your data can be the most time-
consuming part of any data analysis. The most
important steps are considered below. While there are many
approaches, those using the dplyr and tidyr
packages are some of the quickest and easiest to learn.
Package Function Use
dplyr select select variables/columns
dplyr filter select observations/rows
dplyr mutate transform or recode variables
dplyr summarize summarize data
dplyr group_by identify subgroups for further processing
tidyr gather convert wide format dataset to long format
tidyr spread convert long format dataset to wide format
https://db.rstudio.com/rstudio/connections/
1.2. CLEANING DATA 13
Examples in this section will use the starwars dataset from the
dplyr package. The dataset provides
descriptions of 87 characters from the Starwars universe on 13
variables. (I actually prefer StarTrek, but we
work with what we have.)
1.2.1 Selecting variables
The select function allows you to limit your dataset to specified
variables (columns).
library(dplyr)
# keep the variables name, height, and gender
newdata <- select(starwars, name, height, gender)
# keep the variables name and all variables
# between mass and species inclusive
newdata <- select(starwars, name, mass:species)
# keep all variables except birth_year and gender
newdata <- select(starwars, -birth_year, -gender)
1.2.2 Selecting observations
The filter function allows you to limit your dataset to
observations (rows) meeting a specific criteria.
Multiple criteria can be combined with the & (AND) and | (OR)
symbols.
library(dplyr)
# select females
newdata <- filter(starwars,
gender == "female")
# select females that are from Alderaan
newdata <- select(starwars,
gender == "female" &
homeworld == "Alderaan")
# select individuals that are from
# Alderaan, Coruscant, or Endor
newdata <- select(starwars,
homeworld == "Alderaan" |
homeworld == "Coruscant" |
homeworld == "Endor")
# this can be written more succinctly as
newdata <- select(starwars,
homeworld %in% c("Alderaan", "Coruscant", "Endor"))
1.2.3 Creating/Recoding variables
The mutate function allows you to create new variables or
transform existing ones.
14 CHAPTER 1. DATA PREPARATION
library(dplyr)
# convert height in centimeters to inches,
# and mass in kilograms to pounds
newdata <- mutate(starwars,
height = height * 0.394,
mass = mass * 2.205)
The ifelse function (part of base R) can be used for recoding
data. The format is ifelse(test, return
if TRUE, return if FALSE).
library(dplyr)
# if height is greater than 180
# then heightcat = "tall",
# otherwise heightcat = "short"
newdata <- mutate(starwars,
heightcat = ifelse(height > 180,
"tall",
"short")
# convert any eye color that is not
# black, blue or brown, to other
newdata <- mutate(starwars,
eye_color = ifelse(eye_color %in% c("black", "blue", "brown"),
eye_color,
"other")
# set heights greater than 200 or
# less than 75 to missing
newdata <- mutate(starwars,
height = ifelse(height < 75 | height > 200,
NA,
height)
1.2.4 Summarizing data
The summarize function can be used to reduce multiple values
down to a single value (such as a mean). It
is often used in conjunction with the by_group functio n, to
calculate statistics by group. In the code below,
the na.rm=TRUE option is used to drop missing values before
calculating the means.
library(dplyr)
# calculate mean height and mass
newdata <- summarize(starwars,
mean_ht = mean(height, na.rm=TRUE),
mean_mass = mean(mass, na.rm=TRUE))
newdata
## # A tibble: 1 x 2
## mean_ht mean_mass
1.2. CLEANING DATA 15
## <dbl> <dbl>
## 1 174. 97.3
# calculate mean height and weight by gender
newdata <- group_by(starwars, gender)
newdata <- summarize(newdata,
mean_ht = mean(height, na.rm=TRUE),
mean_wt = mean(mass, na.rm=TRUE))
newdata
## # A tibble: 5 x 3
## gender mean_ht mean_wt
## <chr> <dbl> <dbl>
## 1 female 165. 54.0
## 2 hermaphrodite 175. 1358.
## 3 male 179. 81.0
## 4 none 200. 140.
## 5 <NA> 120. 46.3
1.2.5 Using pipes
Packages like dplyr and tidyr allow you to write your code in a
compact format using the pipe %>% operator.
Here is an example.
library(dplyr)
# calculate the mean height for women by species
newdata <- filter(starwars,
gender == "female")
newdata <- group_by(species)
newdata <- summarize(newdata,
mean_ht = mean(height, na.rm = TRUE))
# this can be written as
newdata <- starwars %>%
filter(gender == "female") %>%
group_by(species) %>%
summarize(mean_ht = mean(height, na.rm = TRUE))
The %>% operator passes the result on the left to the first
parameter of the function on the right.
1.2.6 Reshaping data
Some graphs require the data to be in wide format, while some
graphs require the data to be in long format.
You can convert a wide dataset to a long dataset using
library(tidyr)
long_data <- gather(wide_data,
key="variable",
value="value",
sex:income)
16 CHAPTER 1. DATA PREPARATION
Table 1.2: Wide data
id name sex age income
01 Bill Male 22 55000
02 Bob Male 25 75000
03 Mary Female 18 90000
Table 1.3: Long data
id name variable value
01 Bill sex Male
02 Bob sex Male
03 Mary sex Female
01 Bill age 22
02 Bob age 25
03 Mary age 18
01 Bill income 55000
02 Bob income 75000
03 Mary income 90000
Conversely, you can convert a long dataset to a wide dataset
using
library(tidyr)
wide_data <- spread(long_data, variable, value)
1.2.7 Missing data
Real data are likely to contain missing values. There are three
basic approaches to dealing with missing
data: feature selection, listwise deletion, and imputation. Let’s
see how each applies to the msleep dataset
from the ggplot2 package. The msleep dataset describes the
sleep habits of mammals and contains missing
values on several variables.
1.2.7.1 Feature selection
In feature selection, you delete variables (columns) that contain
too many missing values.
data(msleep, package="ggplot2")
# what is the proportion of missing data for each variable?
pctmiss <- colSums(is.na(msleep))/nrow(msleep)
round(pctmiss, 2)
## name genus vore order conservation
## 0.00 0.00 0.08 0.00 0.35
## sleep_total sleep_rem sleep_cycle awake brainwt
## 0.00 0.27 0.61 0.00 0.33
## bodywt
## 0.00
Sixty-one percent of the sleep_cycle values are missing. You
may decide to drop it.
1.2. CLEANING DATA 17
1.2.7.2 Listwise deletion
Listwise deletion involves deleting observations (rows) that
contain missing values on any of the variables of
interest.
# Create a dataset containing genus, vore, and conservation.
# Delete any rows containing missing data.
newdata <- select(msleep, genus, vore, conservation)
newdata <- na.omit(newdata)
1.2.7.3 Imputation
Imputation involves replacing missing values with “reasonable”
guesses about what the values would have
been if they had not been missing. There are several
approaches, as detailed in such packages as VIM, mice,
Amelia and missForest. Here we will use the kNN function from
the VIM package to replace missing values
with imputed values.
# Impute missing values using the 5 nearest neighbors
library(VIM)
newdata <- kNN(msleep, k=5)
Basically, for each case with a missing value, the k most similar
cases not having a missing value are selected.
If the missing value is numeric, the mean of those k cases is
used as the imputed value. If the missing value
is categorical, the most frequent value from the k cases is used.
The process iterates over cases and variables
until the results converge (become stable). This is a bit of an
oversimplification - see Imputation with R
Package VIM for the actual details.
Important caveate: Missing values can bias the results of studies
(sometimes severely). If you
have a significant amount of missing data, it is probably a good
idea to consult a statistician or
data scientist before deleting cases or imputing missing values.
https://www.jstatsoft.org/article/view/v074i07/v74i07.pdf
https://www.jstatsoft.org/article/view/v074i07/v74i07.pdf
18 CHAPTER 1. DATA PREPARATION
Chapter 2
Introduction to ggplot2
This section provides an brief overview of how the ggplot2
package works. If you are simply seeking code to
make a specific type of graph, feel free to skip this section.
However, the material can help you understand
how the pieces fit together.
2.1 A worked example
The functions in the ggplot2 package build up a graph in layers.
We’ll build a a complex graph by starting
with a simple graph and adding additional elements, one at a
time.
The example uses data from the 1985 Current Population Survey
to explore the relationship between wages
(wage) and experience (expr).
# load data
data(CPS85 , package = "mosaicData")
In building a ggplot2 graph, only the first two functions
described below are required. The other functions
are optional and can appear in any order.
2.1.1 ggplot
The first function in building a graph is the ggplot function. It
specifies the
• data frame containing the data to be plotted
• the mapping of the variables to visual properties of the graph.
The mappings are placed within the
aes function (where aes stands for aesthetics).
# specify dataset and mapping
library(ggplot2)
ggplot(data = CPS85,
mapping = aes(x = exper, y = wage))
Why is the graph empty? We specified that the exper variable
should be mapped to the x-axis and that the
wage should be mapped to the y-axis, but we haven’t yet
specified what we wanted placed on the graph.
19
https://ggplot2.tidyverse.org/
20 CHAPTER 2. INTRODUCTION TO GGPLOT2
0
10
20
30
40
0 20 40
exper
w
a
g
e
Figure 2.1: Map variables
2.1. A WORKED EXAMPLE 21
2.1.2 geoms
Geoms are the geometric objects (points, lines, bars, etc.) that
can be placed on a graph. They are added
using functions that start with geom_. In this example, we’ll
add points using the geom_point function,
creating a scatterplot.
In ggplot2 graphs, functions are chained together using the +
sign to build a final plot.
# add points
ggplot(data = CPS85,
mapping = aes(x = exper, y = wage)) +
geom_point()
0
10
20
30
40
0 20 40
exper
w
a
g
e
The graph indicates that there is an outlier. One individual has a
wage much higher than the rest. We’ll
delete this case before continuing.
# delete outlier
library(dplyr)
plotdata <- filter(CPS85, wage < 40)
# redraw scatterplot
ggplot(data = plotdata,
mapping = aes(x = exper, y = wage)) +
geom_point()
A number of parameters (options) can be specified in a geom_
function. Options for the geom_point function
include color, size, and alpha. These control the point color,
size, and transparency, respectively. Trans-
22 CHAPTER 2. INTRODUCTION TO GGPLOT2
0
10
20
0 20 40
exper
w
a
g
e
Figure 2.2: Remove outlier
2.1. A WORKED EXAMPLE 23
0
10
20
0 20 40
exper
w
a
g
e
Figure 2.3: Modify point color, transparency, and size
parency ranges from 0 (completely transparent) to 1 (completely
opaque). Adding a degree of transparency
can help visualize overlapping points.
# make points blue, larger, and semi-transparent
ggplot(data = plotdata,
mapping = aes(x = exper, y = wage)) +
geom_point(color = "cornflowerblue",
alpha = .7,
size = 3)
Next, let’s add a line of best fit. We can do this with the
geom_smooth function. Options control the type of
line (linear, quadratic, nonparametric), the thickness of the line,
the line’s color, and the presence or absence
of a confidence interval. Here we request a linear regression
(method = lm) line (where lm stands for linear
model).
# add a line of best fit.
ggplot(data = plotdata,
mapping = aes(x = exper, y = wage)) +
geom_point(color = "cornflowerblue",
alpha = .7,
size = 3) +
geom_smooth(method = "lm")
Wages appears to increase with experience.
24 CHAPTER 2. INTRODUCTION TO GGPLOT2
0
10
20
0 20 40
exper
w
a
g
e
Figure 2.4: Add line of best fit
2.1. A WORKED EXAMPLE 25
2.1.3 grouping
In addition to mapping variables to the x and y axes, variables
can be mapped to the color, shape, size,
transparency, and other visual characteristics of geometric
objects. This allows groups of observations to be
superimposed in a single graph.
Let’s add sex to the plot and represent it by color.
# indicate sex using color
ggplot(data = plotdata,
mapping = aes(x = exper,
y = wage,
color = sex)) +
geom_point(alpha = .7,
size = 3) +
geom_smooth(method = "lm",
se = FALSE,
size = 1.5)
0
10
20
0 20 40
exper
w
a
g
e
sex
F
M
The color = sex option is placed in the aes function, becaus e we
are mapping a variable to an aesthetic.
The geom_smooth option (se = FALSE) was added to suppresses
the confidence intervals.
It appears that men tend to make more money than women.
Additionally, there may be a stronger relation-
ship between experience and wages for men than than for
women.
26 CHAPTER 2. INTRODUCTION TO GGPLOT2
$0
$5
$10
$15
$20
$25
0 10 20 30 40 50
exper
w
a
g
e
sex
F
M
Figure 2.5: Change colors and axis labels
2.1.4 scales
Scales control how variables are mapped to the visual
characteristics of the plot. Scale functions (which start
with scale_) allow you to modify this mapping. In the next plot,
we’ll change the x and y axis scaling, and
the colors employed.
# modify the x and y axes and specify the colors to be used
ggplot(data = plotdata,
mapping = aes(x = exper,
y = wage,
color = sex)) +
geom_point(alpha = .7,
size = 3) +
geom_smooth(method = "lm",
se = FALSE,
size = …
Patient Case #3
Patient: Rashid Ahmed
Diagnosis: Dehydration and hypokalemia
Brief Summary:
Rashid Ahmed is a 50-year-old Middle Eastern male who was
admitted this morning to the medical unit with a diagnosis of
dehydration and hypokalemia. He has been experiencing nausea,
vomiting, and diarrhea for the past 48 hours after eating at a
local restaurant three days ago.
Medications:
· Trimethoprim/Sulfamethoxazole 160/800 mg PO q12h
· Potassium chloride (KCL) 40 mEq PO once
· Ondansetron 4 mg IV push q6h prn for nausea
· Lisinopril 5mg PO daily
· Atorvastatin 10mg PO nightly
Orders:
· Vital signs every 4 hours and prn
· Daily weights
· Activity: Up ad lib with assistance x1
· Diet: Clear liquids, progress to regular as tolerated
· IV: 1000 mL dextrose 5% in normal saline with 20 mEq KCL
at 125 mL/hr
· Intake and output, record every 8 hours
SBAR Report:
S: Mr. Rashid Ahmed is a 50-year-old Middle Eastern male who
was admitted to our unit at 0600 this morning after being
admitted to the ED at 0400 with a diagnosis of dehydration and
hypokalemia. We are monitoring his fluid and electrolyte status
closely. I have just received admission orders.
B: Three days ago, he developed abdominal cramping, nausea,
vomiting, and severe diarrhea 12 hours after eating lunch at a
local restaurant. The symptoms have continued for the past 2
days, and food and fluid intake has been minimal to none since
the symptoms began. Last night he nearly passed out while
going to the bathroom around 0300. Mr. Ahmed was brought to
the ED by his wife, and reported dizziness, weakness, and
continued nausea. He received 4 mg ondansetron IV for nausea
in the ED. Lab work was drawn and is available in the patient
chart, and urine and stool samples have been sent to the lab. Mr.
Ahmed’s only medical history includes hypertension and
hyperlipidemia.
A: Mr. Ahmed is drowsy but oriented x 3, appears ill, and is
irritable. He reports having a headache, which he rates a 4 on a
scale of 0–10, but he hasn't wanted anything for it. Admission
weight was 73 kg (162 lb), which the patient reports to be about
4.5 kg (10 lb) less than usual. Vital signs were obtained on
admission, including orthostatic blood pressure readings which
were positive. Patient had drop in BP from 135/70 while lying
down to 105/55 once he stood up. He reports dizziness. Heart
rate is tachycardic and irregular. Patient also noted to have a
100.4 degree temperature. He has only taken a few ice chips
since admission due to his nausea. The patient had one small
liquid stool in the ER. He has not voided or experienced emesis
since admission. An IV bolus has been completed and now
D5NS IV fluids are running at 125 mL/hr.
R: Mr. Ahmed has new IV orders that need to be initiated. You
will need to start him on oral antibiotics and potassium when
nausea resolves. Provide patient education on safety, his
prescribed medications, and intake and output measurement.
Patient Case Scenario #1
Chris Parrish
Patient: Christopher Parrish
Diagnosis: Cystic fibrosis, weight loss, and fatigue
Brief Summary:
Christopher Parrish is an 18-year-old adolescent male who is
hospitalized for management of cystic fibrosis with weakness
and weight loss. He reports fatigue, and he has had a recent 6 kg
(13.2 lb) weight loss. Hewas diagnosed with cystic fibrosis as
an infant and has had multiple hospitalizations for respiratory
and nutritional support. A nasogastric (NG) tube has been
placed for feedings.
Medications:
· Pancrelipase supplement 5 capsules PO QID with meals and at
start of nightly tube feeding
· Multivitamin 2 tabs PO daily
· Potassium chloride 40 mEq PO daily
Orders:
· Vital signs every 4 hours
· Daily intake and output, and weight
· Chest X-ray: AP and lateral tomorrow morning
· Insert nasogastric tube
· Nutrition consult
· Diet: High-fat, high-calorie, high-protein regular diet,
supplement with high-protein snacks in between meals
· Promote tube feedings (1.5 kcal/mL) in nasogastric tube;
administer 720 kcal over 8 hours at night (infuse via pump from
2200-0600)
SBAR:
S: Christopher Parrish is an 19-year-old male who was admitted
at 1900 today. His mother visited him at his college dormitory
and was very concerned with his health; he seemed weak and
had lost weight since she last saw him. She took him to see his
primary care provider, and the provider admitted him and has
ordered a tube feeding. An 8-French, 42-inch feeding tube was
placed in his right nare about an hour ago, and x-ray just called
and confirmed placement in the stomach. The pump is in his
room. He is up to the bathroom prn; otherwise bed rest.
B: Christopher was diagnosed with cystic fibrosis as a child and
has had frequent hospitalizations previously. He reports fatigue
and has recently lost 6 kg (13.2 lb) after he registered at the
local college and moved to live in a dormitory, one month ago.
Chris's mom was here earlier, but she is a single parent and has
two younger boys, so she had to go home.
A: Christopher is awake and alert. His heart rate and rhythm are
regular at 85 bpm. Breath sounds are fine with a respiratory rate
at 18/min and his SpO2 saturation is 98% on room air. His color
is a bit pale. Blood pressure is 118/78 mm Hg. He reports no
pain and states he's not had much appetite the past few weeks.
His skin turgor is > 3 seconds and his mucous membranes are
dry. His belly is flat and nontender. Bowel sounds are
normoactive. Chris is noted to have a persistent productive
cough, and his sputum is noted to be thick and yellow in color.
Chris tends to get short of breath with any strenuous activity.
He was noted to become short of breath, with an increase in RR
to 26 bpm, after walking in the hallway for about 10 minutes.
His potassium level this morning was low at 3.2 mEq/L.
R: Christopher is due for vital signs and assessment. The tube
feeding just arrived, and you will need to start it on the pump.
He needs 720 kilocalories over 8 hours overnight. His regular
diet is high calorie, high fat, but he wasn't too hungry this
evening; just had a bit of his chocolate shake. You will need to
give his pancreatic enzymes orally before you start the tube
feeding. You should also assess his diet and reinforce patient
education on nutrition.
NRG5000 Theoretical Foundations of Nursing
Dr. Lisa Capps, Faculty
1
Concept Map and Care Plan (Clinical Assignment #2) Grading
Rubric
Student Name:
__________________________________________________
Description
Points Received/
Total Points Possible
Comments
Diagnosis #1
Diagnosis #2
Totals
Patient Information and Health Assessments
· Complete patient demographics, health assessments, and
interventions
____/ 3
Pharmacology:
· Complete& accurate description of current meds, including
purpose for this patient, side effects, and all other data listed in
chart
____/ 3
Pathophysiology:
· Includes “signs and symptoms”
· Includes APA references cited
____/ 3
Nursing Diagnosis (Include ALL 2 Dx):
· Reflects the primary diagnosis
· Appropriate for patient scenario as well as priority level
· In acceptable NANDA format
· Includes all parts stem, R/T, AEB
· Only 1 ‘Risk For’ diagnosis can be used
____/ 3
Provided 2 nursing diagnoses: 2 points per diagnosis
____/ 4
Assessment:
· Appropriate for chosen diagnosis
· Includes objective & subjective historical support diagnosing
data
____/3
+ ____/3
= ____/ 6
Patient Outcomes:
· Include at least 2 outcomes for each diagnosis
· Specific to the patient diagnosis
· Contains the following 4 criteria:
measurable, attainable, realistic, and timed
· All criteria present for patient’s expected outcome
____/3
+ ____/3
= ____/ 6
Intervention/Implementation:
· Include at least 3 nursing interventions for each patient
outcome
· Includes interventions/ nursing actions directly relating to pt.
outcomes
· Specific in action, frequency and contain rationale
· # of interventions is appropriate to help pt./ family meet their
outcomes
____/3
+ ____/3
= ____/ 6
Evaluation:
· Must have an evaluation statement written for each patient
outcome
· Includes all data that is listed as criteria in outcomes
· Outcomes are determined to be met, partially met, or not met
· If outcome was not met/ partially met, plan of care is revised/
continued & new evaluation date/time is set
____/3
+ ____/3
= ____/ 6
Total Points: ____/ 40
Patient Case #2
Patient: Edith Jacobson
Diagnosis: Left hip fracture
Brief Summary:
Edith Jacobson is an 85-year-old white female with a history of
osteoporosis. She lives at home by herself where she fell and
broke her left hip yesterday evening, after having complaints of
dizziness, weakness, and fatigue. She is scheduled to have
surgery in 2 days.
Medications:
· Enoxaparin sodium 40 mg SQ daily
· Docusate sodium 100 mg PO daily
· Morphine sulfate 4 mg IV q4h prn for pain
· Metoprolol 25 mg PO BID
· Furosemide 20mg PO daily
Orders:
· Vital signs every 4 hours
· Activity: Bed rest
· Anti-embolism stockings on both legs (knee-length)
SBAR Report:
S: Mrs. Jacobson is an 85-year-old white female who was
admitted last evening after falling and fracturing her hip. X-rays
have been taken and show left intertrochanteric hip fracture.
Mrs. Jacobson is scheduled for surgery in 2 days.
B: Mrs. Jacobson has a 10-year history of osteoporosis and was
newly diagnosed with congestive heart failure last year. Her
daughter reports that recently Mrs. Jacobson has been having
dizzy spells, fatigue, and weakness. Mrs. Jacobson lives alone
and is usually able to perform all her ADLs independently. She
does have a cane at home but often times refuses to use it
because she “doesn’t think she needs it”. Mrs. Jacobson is
usually pretty active, but has been much more sedentary lately
due to increasing weakness and fatigue due to medication non-
compliance with her heart failure medications.
A: Mrs. Jacobson is AOx4 and her vital signs are stable. Her
pain level is currently a 7 out of 10, and she describes is as
“throbbing and aching” in her left hip. Often times Mrs.
Jacobson will moan or cry out in pain, especially whenever she
needs to be moved in bed. She is very resistant to let anyone
touch or move her left leg. The skin is intact; color and
sensation around the hip area are within normal limits. A Morse
Fall Scale assessment was completed on admission, and her
score was 45. Fall precautions were implemented. Mrs.
Jacobson has limited ROM in her left hip and her muscle
strength in her left lower extremity is weak at a 2/5. Mrs.
Jacobson has been having some episodes of urinary and bowel
incontinence since being admitted to the hospital. She
frequently needs to be reminded that she cannot get out of bed
due to her activity restriction.
R: You will need to reposition Mrs. Jacobson as she needs to be
turned every 2 hours. You should perform a focused
musculoskeletal assessment, reinforce safety, and provide
patient education on fall risk. Assess her pain level and
medicate for pain if needed.
Patient Case #4
Patient: Vernon Russell
Diagnosis: Right-sided stroke (mild left hemiplegia)
Brief Summary:
Vernon Russell is a 55-year-old Native American male who was
admitted with a stroke with mild left hemiplegia yesterday. The
patient is nothing by mouth except medications. Chest-x-ray
confirmed possible aspiration pneumonia on the right side.
Medications:
· Losartan 50 mg PO BID
· Aspirin 81 mg PO daily
· Metformin 500 mg PO BID
· Chlorthalidone 25 mg PO daily
Orders:
· Vital signs and neuro checks every 4 hours
· Activity: Up to chair, up to the bathroom with assistance
· Nothing by mouth except medications until swallow study
completed tomorrow
· Speech therapist swallow study
· Fall risk assessment
· Labs: CBC, chemistry panel, and prothrombin time
· Bedside blood glucose twice a day
SBAR Report:
S: Mr. Russell is a 55-year-old Native American male who was
admitted with a stroke with mild left hemiplegia yesterday
afternoon. He had a head CT and received thrombolytic therapy
in the ED. He is nothing by mouth except for medications until
the speech therapist has completed a video swallow study,
which is scheduled for later this morning. He is scheduled for
physical therapy later today.
B: Mr. Russell has a history of hypertension, coronary artery
disease, and diabetes mellitus type 2. He has smoked over a
pack of cigarettes per day for the past 35 years and does not
exercise.
A: We have already checked his blood glucose level this
morning. His vital signs have been stable and he slept well last
night. He was able to get up to go to the bathroom with the use
of a walker. His neurological checks are stable and he continues
to have mild left hemiplegia. His hand grasps are almost equal
but a little weaker on the left side. His pupils are equal and
react to light. Swallow reflex is intact but impaired. He is
oriented x2. Patient is slow to respond and noted to have some
periods of slurred or delayed speech. I have already done a
Morse Fall Risk assessment with a total high risk score of 60.
Fall precautions implemented. Upon bedside RN swallow
evaluation, the patient was noted to have frequent coughing
when given a small sip of water. Chest x-ray done in the ED
reveals that the patient has right-sided pneumonia, possibly due
to aspiration.
R: You should do a vital signs assessment, perform a
neurological assessment, and talk about safety with Mr. Russell.
His morning medications are up and should be administered
with caution. Maintain NPO status until video swallow
performed. Patient was able to stand on side of bed with
physical therapist, but weakness noted. Patient unable to take
steps. Continue fall and aspiration precautions.

More Related Content

DOCX
Data visualization with r rob kabacoff2018 09-032
PDF
PDF
Rlecturenotes
PDF
Stronghold manual
PDF
Networkx 0.99
PDF
Wedit window function
PDF
Begining j2 me
PDF
Math for programmers
Data visualization with r rob kabacoff2018 09-032
Rlecturenotes
Stronghold manual
Networkx 0.99
Wedit window function
Begining j2 me
Math for programmers

What's hot (18)

PDF
PDF
PSA user manual
PDF
User manual
PDF
User manual
PDF
User manual
PDF
User manual PSPP
PDF
Openbravo er diagram_1_0
PDF
Addendum
PDF
Rprogramming
PDF
Optimization of an Energy-Generating Turnstile
PDF
Uni cambridge
 
PDF
Qgis 1.7.0 user-guide_en
PDF
Creating Scientific Posters
PDF
thesis
PDF
Coding interview preparation
PDF
PDF
Architectural Survey - N7 Castletown-Nenagh Road Scheme
PSA user manual
User manual
User manual
User manual
User manual PSPP
Openbravo er diagram_1_0
Addendum
Rprogramming
Optimization of an Energy-Generating Turnstile
Uni cambridge
 
Qgis 1.7.0 user-guide_en
Creating Scientific Posters
thesis
Coding interview preparation
Architectural Survey - N7 Castletown-Nenagh Road Scheme
Ad

Similar to Concept mapping patient initials, age, gender and admitting d (20)

DOCX
Data Visualization with RRob Kabacoff2018-09-032
PDF
R data mining_clear
PDF
An Introduction To R Software For Statistical Modelling Computing Course M...
PDF
Using R For Data Management Statistical Analysis And Graphics 1st Edition Nic...
PDF
Handbook Of Data Visualization Springer Handbooks Of Computational Statistics...
PDF
Vivarana fyp report
PDF
Applied Statistics With R
DOCX
ContentsPreface vii1 Introduction 11.1 What .docx
PDF
PDF
Scikit learn 0.16.0 user guide
PDF
Wes McKinney - Python for Data Analysis-O'Reilly Media (2012).pdf
PDF
Introduction to R Short course Fall 2016
PDF
spss Amos 20 user_guide
PDF
book.pdf
PDF
pyspark.pdf
PDF
Science Online 2013: Data Visualization Using R
PDF
Data analysis with R.pdf
PDF
PDF
Baron rpsych
PDF
Machine learning-a-z-q-a
Data Visualization with RRob Kabacoff2018-09-032
R data mining_clear
An Introduction To R Software For Statistical Modelling Computing Course M...
Using R For Data Management Statistical Analysis And Graphics 1st Edition Nic...
Handbook Of Data Visualization Springer Handbooks Of Computational Statistics...
Vivarana fyp report
Applied Statistics With R
ContentsPreface vii1 Introduction 11.1 What .docx
Scikit learn 0.16.0 user guide
Wes McKinney - Python for Data Analysis-O'Reilly Media (2012).pdf
Introduction to R Short course Fall 2016
spss Amos 20 user_guide
book.pdf
pyspark.pdf
Science Online 2013: Data Visualization Using R
Data analysis with R.pdf
Baron rpsych
Machine learning-a-z-q-a
Ad

More from ARIV4 (20)

DOCX
Please go through the document completely before providing the answe.docx
DOCX
Please follow the instruction carefully. APA stile. Mínimum three re.docx
DOCX
Please follow the instructions attached in MS Word. Font Arial,  .docx
DOCX
Please help me write a report focusing on photocatalysis of TiO2 .docx
DOCX
Please follow the directions in the assignment content Environme.docx
DOCX
Please follow the directions below to complete the project1.).docx
DOCX
Please follow all directions please. the attachment titled assignme.docx
DOCX
Please draft a personal message that you would like to appear on you.docx
DOCX
Please explain how you have met various BSN Essentials for each co.docx
DOCX
Please Follow directions or I will dispute please answer origina.docx
DOCX
Please find the attached.Task 1 -  In 150 words comment on att.docx
DOCX
Please draw primarily from this weeks readings (and use additio.docx
DOCX
Please explain the reoccurring theme (sub-textual idea) of blin.docx
DOCX
Please fill the attached Self-Assessment Surveys (TWO) and calcula.docx
DOCX
Please explain the rules of the calling program (Caller Rules).docx
DOCX
Please follow directions to receive all possible points!!The int.docx
DOCX
Please follow instructions A blanch interpersonal record attached..docx
DOCX
Please explain how you have met various BSN Essentials for each cour.docx
DOCX
Please explain how you have met various Bachelor of Science in Nur.docx
DOCX
Please DiscussWhat are host-based, client-based, client-serv.docx
Please go through the document completely before providing the answe.docx
Please follow the instruction carefully. APA stile. Mínimum three re.docx
Please follow the instructions attached in MS Word. Font Arial,  .docx
Please help me write a report focusing on photocatalysis of TiO2 .docx
Please follow the directions in the assignment content Environme.docx
Please follow the directions below to complete the project1.).docx
Please follow all directions please. the attachment titled assignme.docx
Please draft a personal message that you would like to appear on you.docx
Please explain how you have met various BSN Essentials for each co.docx
Please Follow directions or I will dispute please answer origina.docx
Please find the attached.Task 1 -  In 150 words comment on att.docx
Please draw primarily from this weeks readings (and use additio.docx
Please explain the reoccurring theme (sub-textual idea) of blin.docx
Please fill the attached Self-Assessment Surveys (TWO) and calcula.docx
Please explain the rules of the calling program (Caller Rules).docx
Please follow directions to receive all possible points!!The int.docx
Please follow instructions A blanch interpersonal record attached..docx
Please explain how you have met various BSN Essentials for each cour.docx
Please explain how you have met various Bachelor of Science in Nur.docx
Please DiscussWhat are host-based, client-based, client-serv.docx

Recently uploaded (20)

PPTX
GDM (1) (1).pptx small presentation for students
PPTX
Final Presentation General Medicine 03-08-2024.pptx
PDF
Yogi Goddess Pres Conference Studio Updates
PDF
GENETICS IN BIOLOGY IN SECONDARY LEVEL FORM 3
PDF
Supply Chain Operations Speaking Notes -ICLT Program
PDF
RMMM.pdf make it easy to upload and study
PDF
Microbial disease of the cardiovascular and lymphatic systems
PDF
A systematic review of self-coping strategies used by university students to ...
PPTX
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
PDF
Computing-Curriculum for Schools in Ghana
PDF
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
PPTX
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
PDF
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
PDF
OBE - B.A.(HON'S) IN INTERIOR ARCHITECTURE -Ar.MOHIUDDIN.pdf
PDF
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
PPTX
Tissue processing ( HISTOPATHOLOGICAL TECHNIQUE
PDF
VCE English Exam - Section C Student Revision Booklet
PDF
01-Introduction-to-Information-Management.pdf
PDF
STATICS OF THE RIGID BODIES Hibbelers.pdf
PDF
O5-L3 Freight Transport Ops (International) V1.pdf
GDM (1) (1).pptx small presentation for students
Final Presentation General Medicine 03-08-2024.pptx
Yogi Goddess Pres Conference Studio Updates
GENETICS IN BIOLOGY IN SECONDARY LEVEL FORM 3
Supply Chain Operations Speaking Notes -ICLT Program
RMMM.pdf make it easy to upload and study
Microbial disease of the cardiovascular and lymphatic systems
A systematic review of self-coping strategies used by university students to ...
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
Computing-Curriculum for Schools in Ghana
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
OBE - B.A.(HON'S) IN INTERIOR ARCHITECTURE -Ar.MOHIUDDIN.pdf
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
Tissue processing ( HISTOPATHOLOGICAL TECHNIQUE
VCE English Exam - Section C Student Revision Booklet
01-Introduction-to-Information-Management.pdf
STATICS OF THE RIGID BODIES Hibbelers.pdf
O5-L3 Freight Transport Ops (International) V1.pdf

Concept mapping patient initials, age, gender and admitting d

  • 1. Concept Mapping Patient initials, age, gender and admitting diagnosis Nursing diagnosis Related to As Evidence by Nursing diagnosis Related to As Evidence by Outcomes Assessment Signs / Symptoms Subjective / Objective Outcomes Assessment Signs / Symptoms Subjective / Objective
  • 2. Interventions Interventions Evaluation of Interventions / Outcomes Medication Dose, Route & Frequency Classification Purpose / Mechanism of Action Significant Side Effects / Adverse Reactions Nursing Implications
  • 5. 1. APA format (citations and references) 2. Discuss the disease process: etiology, epidemiology, and pathophysiologic mechanism 3. Identify common complications that may occur with the alterations or treatment modalities 4. Patient’s overall prognosis Data Visualization with R Rob Kabacoff 2018-09-03 2 Contents Welcome 7 Preface 9 How to use this book . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9 Prequisites . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10 Setup . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10 1 Data Preparation 11
  • 6. 1.1 Importing data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11 1.2 Cleaning data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12 2 Introduction to ggplot2 19 2.1 A worked example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19 2.2 Placing the data and mapping options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30 2.3 Graphs as objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32 3 Univariate Graphs 35 3.1 Categorical . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35 3.2 Quantitative . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51 4 Bivariate Graphs 63 4.1 Categorical vs. Categorical . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63 4.2 Quantitative vs. Quantitative . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71 4.3 Categorical vs. Quantitative . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79
  • 7. 5 Multivariate Graphs 103 5.1 Grouping . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103 6 Maps 115 6.1 Dot density maps . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115 6.2 Choropleth maps . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119 3 4 CONTENTS 7 Time-dependent graphs 127 7.1 Time series . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127 7.2 Dummbbell charts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 130 7.3 Slope graphs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 133 7.4 Area Charts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 135 8 Statistical Models 139
  • 8. 8.1 Correlation plots . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 139 8.2 Linear Regression . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 141 8.3 Logistic regression . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 145 8.4 Survival plots . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 147 8.5 Mosaic plots . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 150 9 Other Graphs 153 9.1 3-D Scatterplot . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 153 9.2 Biplots . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 159 9.3 Bubble charts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 161 9.4 Flow diagrams . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 163 9.5 Heatmaps . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 168 9.6 Radar charts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 174 9.7 Scatterplot matrix . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
  • 9. . . . . . . . . . . . 176 9.8 Waterfall charts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 178 9.9 Word clouds . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 180 10 Customizing Graphs 183 10.1 Axes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 183 10.2 Colors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 187 10.3 Points & Lines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 193 10.4 Legends . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 195 10.5 Labels . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 197 10.6 Annotations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 199 10.7 Themes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 206 11 Saving Graphs 219 11.1 Via menus . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 219
  • 10. 11.2 Via code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 219 11.3 File formats . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 219 11.4 External editing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 221 CONTENTS 5 12 Interactive Graphs 223 12.1 leaflet . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 223 12.2 plotly . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 223 12.3 rbokeh . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 226 12.4 rCharts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 226 12.5 highcharter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 226 13 Advice / Best Practices 231 13.1 Labeling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 231 13.2 Signal to noise ratio . . . . . . . . . . . . . . . . . . . . . . . . . . . .
  • 11. . . . . . . . . . . . . . 232 13.3 Color choice . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 234 13.4 y-Axis scaling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 234 13.5 Attribution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 238 13.6 Going further . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 238 13.7 Final Note . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 239 A Datasets 241 A.1 Academic salaries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 241 A.2 Starwars . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 241 A.3 Mammal sleep . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 241 A.4 Marriage records . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 242 A.5 Fuel economy data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 242 A.6 Gapminder data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 242
  • 12. A.7 Current Population Survey (1985) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 242 A.8 Houston crime data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 242 A.9 US economic timeseries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 243 A.10 Saratoga housing data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 243 A.11 US population by age and year . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 243 A.12 NCCTG lung cancer data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 243 A.13 Titanic data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 243 A.14 JFK Cuban Missle speech . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 244 A.15 UK Energy forecast data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 244 A.16 US Mexican American Population . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 244 B About the Author 245 C About the QAC 247
  • 13. 6 CONTENTS Welcome R is an amazing platform for data analysis, capable of creating almost any type of graph. This book helps you create the most popular visualizations - from quick and dirty plots to publication-ready graphs. The text relies heavily on the ggplot2 package for graphics, but other approaches are covered as well. This work is licensed under a Creative Commons Attribution- NonCommercial-NoDerivatives 4.0 Interna- tional License. My goal is make this book as helpful and user-friendly as possible. Any feedback is both welcome and appreciated. 7 8 CONTENTS Preface How to use this book You don’t need to read this book from start to finish in order to start building effective graphs. Feel free to
  • 14. jump to the section that you need and then explore others that you find interesting. Graphs are organized by • the number of variables to be plotted • the type of variables to be plotted • the purpose of the visualization Chapter Description Ch 1 provides a quick overview of how to get your data into R and how to prepare it for analysis. Ch 2 provides an overview of the ggplot2 package. Ch 3 describes graphs for visualizing the distribution of a single categorical (e.g. race) or quantitative (e.g. income) variable. Ch 4 describes graphs that display the relationship between two variables. Ch 5 describes graphs that display the relationships among 3 or more variables. It is helpful to read chapters 3 and 4 before this chapter. Ch 6 provides a brief introduction to displaying data geographically. Ch 7 describes graphs that display change over time. Ch 8 describes graphs that can help you interpret the results of statistical models. Ch 9 covers graphs that do not fit neatly elsewhere (every book needs a miscellaneous chapter). Ch 10 describes how to customize the look and feel of your
  • 15. graphs. If you are going to share your graphs with others, be sure to skim this chapter. Ch 11 covers how to save your graphs. Different formats are optimized for different purposes. Ch 12 provides an introduction to interactive graphics. Ch 13 gives advice on creating effective graphs and where to go to learn more. It’s worth a look. The Appendices describe each of the datasets used in this book, and provides a short blurb about the author and the Wesleyan Quantitative Analysis Center. There is no one right graph for displaying data. Check out the examples, and see which type best fits your needs. 9 10 CONTENTS Prequisites It’s assumed that you have some experience with the R language and that you have already installed R and RStudio. If not, here are some resources for getting started: • A (very) short introduction to R • DataCamp - Introduction to R with Jonathon Cornelissen • Quick-R
  • 16. • Getting up to speed with R Setup In order to create the graphs in this guide, you’ll need to install some optional R packages. To install all of the necessary packages, run the following code in the RStudio console window. pkgs <- c("ggplot2", "dplyr", "tidyr", "mosaicData", "carData", "VIM", "scales", "treemapify", "gapminder", "ggmap", "choroplethr", "choroplethrMaps", "CGPfunctions", "ggcorrplot", "visreg", "gcookbook", "forcats", "survival", "survminer", "ggalluvial", "ggridges", "GGally", "superheat", "waterfalls", "factoextra", "networkD3", "ggthemes", "hrbrthemes", "ggpol", "ggbeeswarm") install.packages(pkgs) Alternatively, you can install a given package the first time it is needed. For example, if you execute library(gapminder) and get the message Error in library(gapminder) : there is no package called
  • 17. ‘gapminder’ you know that the package has never been installed. Simply execute install.packages("gapminder") once and library(gapminder) will work from that point on. https://cran.r-project.org/ https://www.rstudio.com/products/RStudio/#Desktop https://cran.r-project.org/doc/contrib/Torfs+Brauer-Short-R- Intro.pdf https://www.datacamp.com/courses/free-introduction-to-r http://www.statmethods.net Chapter 1 Data Preparation Before you can visualize your data, you have to get it into R. This involves importing the data from an external source and massaging it into a useful format. 1.1 Importing data R can import data from almost any source, including text files, excel spreadsheets, statistical packages, and database management systems. We’ll illustrate these techniques using the Salaries dataset, containing the 9 month academic salaries of college professors at a single
  • 18. institution in 2008-2009. 1.1.1 Text files The readr package provides functions for importing delimited text files into R data frames. library(readr) # import data from a comma delimited file Salaries <- read_csv("salaries.csv") # import data from a tab delimited file Salaries <- read_tsv("salaries.txt") These function assume that the first line of data contains the variable names, values are separated by commas or tabs respectively, and that missing data are represented by blanks. For example, the first few lines of the comma delimited file looks like this. "rank","discipline","yrs.since.phd","yrs.service","sex","salary" "Prof","B",19,18,"Male",139750 "Prof","B",20,16,"Male",173200 "AsstProf","B",4,3,"Male",79750 "Prof","B",45,39,"Male",115000 "Prof","B",40,41,"Male",141500 "AssocProf","B",6,6,"Male",97000 Options allow you to alter these assumptions. See the documentation for more details. 11 https://www.rdocumentation.org/packages/readr/versions/0.1.1/t opics/read_delim
  • 19. 12 CHAPTER 1. DATA PREPARATION 1.1.2 Excel spreadsheets The readxl package can import data from Excel workbooks. Both xls and xlsx formats are supported. library(readxl) # import data from an Excel workbook Salaries <- read_excel("salaries.xlsx", sheet=1) Since workbooks can have more than one worksheet, you can specify the one you want with the sheet option. The default is sheet=1. 1.1.3 Statistical packages The haven package provides functions for importing data from a variety of statistical packages. library(haven) # import data from Stata Salaries <- read_dta("salaries.dta") # import data from SPSS Salaries <- read_sav("salaries.sav") # import data from SAS Salaries <- read_sas("salaries.sas7bdat") 1.1.4 Databases
  • 20. Importing data from a database requires additional steps and is beyond the scope of this book. Depending on the database containing the data, the following packages can help: RODBC, RMySQL, ROracle, RPostgreSQL, RSQLite, and RMongo. In the newest versions of RStudio, you can use the Connections pane to quickly access the data stored in database management systems. 1.2 Cleaning data The processes of cleaning your data can be the most time- consuming part of any data analysis. The most important steps are considered below. While there are many approaches, those using the dplyr and tidyr packages are some of the quickest and easiest to learn. Package Function Use dplyr select select variables/columns dplyr filter select observations/rows dplyr mutate transform or recode variables dplyr summarize summarize data dplyr group_by identify subgroups for further processing tidyr gather convert wide format dataset to long format tidyr spread convert long format dataset to wide format https://db.rstudio.com/rstudio/connections/ 1.2. CLEANING DATA 13 Examples in this section will use the starwars dataset from the dplyr package. The dataset provides descriptions of 87 characters from the Starwars universe on 13 variables. (I actually prefer StarTrek, but we work with what we have.)
  • 21. 1.2.1 Selecting variables The select function allows you to limit your dataset to specified variables (columns). library(dplyr) # keep the variables name, height, and gender newdata <- select(starwars, name, height, gender) # keep the variables name and all variables # between mass and species inclusive newdata <- select(starwars, name, mass:species) # keep all variables except birth_year and gender newdata <- select(starwars, -birth_year, -gender) 1.2.2 Selecting observations The filter function allows you to limit your dataset to observations (rows) meeting a specific criteria. Multiple criteria can be combined with the & (AND) and | (OR) symbols. library(dplyr) # select females newdata <- filter(starwars, gender == "female") # select females that are from Alderaan newdata <- select(starwars, gender == "female" & homeworld == "Alderaan")
  • 22. # select individuals that are from # Alderaan, Coruscant, or Endor newdata <- select(starwars, homeworld == "Alderaan" | homeworld == "Coruscant" | homeworld == "Endor") # this can be written more succinctly as newdata <- select(starwars, homeworld %in% c("Alderaan", "Coruscant", "Endor")) 1.2.3 Creating/Recoding variables The mutate function allows you to create new variables or transform existing ones. 14 CHAPTER 1. DATA PREPARATION library(dplyr) # convert height in centimeters to inches, # and mass in kilograms to pounds newdata <- mutate(starwars, height = height * 0.394, mass = mass * 2.205) The ifelse function (part of base R) can be used for recoding data. The format is ifelse(test, return if TRUE, return if FALSE).
  • 23. library(dplyr) # if height is greater than 180 # then heightcat = "tall", # otherwise heightcat = "short" newdata <- mutate(starwars, heightcat = ifelse(height > 180, "tall", "short") # convert any eye color that is not # black, blue or brown, to other newdata <- mutate(starwars, eye_color = ifelse(eye_color %in% c("black", "blue", "brown"), eye_color, "other") # set heights greater than 200 or # less than 75 to missing newdata <- mutate(starwars, height = ifelse(height < 75 | height > 200, NA, height) 1.2.4 Summarizing data The summarize function can be used to reduce multiple values down to a single value (such as a mean). It is often used in conjunction with the by_group functio n, to calculate statistics by group. In the code below, the na.rm=TRUE option is used to drop missing values before calculating the means.
  • 24. library(dplyr) # calculate mean height and mass newdata <- summarize(starwars, mean_ht = mean(height, na.rm=TRUE), mean_mass = mean(mass, na.rm=TRUE)) newdata ## # A tibble: 1 x 2 ## mean_ht mean_mass 1.2. CLEANING DATA 15 ## <dbl> <dbl> ## 1 174. 97.3 # calculate mean height and weight by gender newdata <- group_by(starwars, gender) newdata <- summarize(newdata, mean_ht = mean(height, na.rm=TRUE), mean_wt = mean(mass, na.rm=TRUE)) newdata ## # A tibble: 5 x 3 ## gender mean_ht mean_wt ## <chr> <dbl> <dbl> ## 1 female 165. 54.0 ## 2 hermaphrodite 175. 1358. ## 3 male 179. 81.0
  • 25. ## 4 none 200. 140. ## 5 <NA> 120. 46.3 1.2.5 Using pipes Packages like dplyr and tidyr allow you to write your code in a compact format using the pipe %>% operator. Here is an example. library(dplyr) # calculate the mean height for women by species newdata <- filter(starwars, gender == "female") newdata <- group_by(species) newdata <- summarize(newdata, mean_ht = mean(height, na.rm = TRUE)) # this can be written as newdata <- starwars %>% filter(gender == "female") %>% group_by(species) %>% summarize(mean_ht = mean(height, na.rm = TRUE)) The %>% operator passes the result on the left to the first parameter of the function on the right. 1.2.6 Reshaping data Some graphs require the data to be in wide format, while some graphs require the data to be in long format. You can convert a wide dataset to a long dataset using
  • 26. library(tidyr) long_data <- gather(wide_data, key="variable", value="value", sex:income) 16 CHAPTER 1. DATA PREPARATION Table 1.2: Wide data id name sex age income 01 Bill Male 22 55000 02 Bob Male 25 75000 03 Mary Female 18 90000 Table 1.3: Long data id name variable value 01 Bill sex Male 02 Bob sex Male 03 Mary sex Female 01 Bill age 22 02 Bob age 25 03 Mary age 18 01 Bill income 55000 02 Bob income 75000 03 Mary income 90000 Conversely, you can convert a long dataset to a wide dataset using library(tidyr) wide_data <- spread(long_data, variable, value)
  • 27. 1.2.7 Missing data Real data are likely to contain missing values. There are three basic approaches to dealing with missing data: feature selection, listwise deletion, and imputation. Let’s see how each applies to the msleep dataset from the ggplot2 package. The msleep dataset describes the sleep habits of mammals and contains missing values on several variables. 1.2.7.1 Feature selection In feature selection, you delete variables (columns) that contain too many missing values. data(msleep, package="ggplot2") # what is the proportion of missing data for each variable? pctmiss <- colSums(is.na(msleep))/nrow(msleep) round(pctmiss, 2) ## name genus vore order conservation ## 0.00 0.00 0.08 0.00 0.35 ## sleep_total sleep_rem sleep_cycle awake brainwt ## 0.00 0.27 0.61 0.00 0.33 ## bodywt ## 0.00 Sixty-one percent of the sleep_cycle values are missing. You may decide to drop it. 1.2. CLEANING DATA 17
  • 28. 1.2.7.2 Listwise deletion Listwise deletion involves deleting observations (rows) that contain missing values on any of the variables of interest. # Create a dataset containing genus, vore, and conservation. # Delete any rows containing missing data. newdata <- select(msleep, genus, vore, conservation) newdata <- na.omit(newdata) 1.2.7.3 Imputation Imputation involves replacing missing values with “reasonable” guesses about what the values would have been if they had not been missing. There are several approaches, as detailed in such packages as VIM, mice, Amelia and missForest. Here we will use the kNN function from the VIM package to replace missing values with imputed values. # Impute missing values using the 5 nearest neighbors library(VIM) newdata <- kNN(msleep, k=5) Basically, for each case with a missing value, the k most similar cases not having a missing value are selected. If the missing value is numeric, the mean of those k cases is used as the imputed value. If the missing value is categorical, the most frequent value from the k cases is used. The process iterates over cases and variables until the results converge (become stable). This is a bit of an oversimplification - see Imputation with R Package VIM for the actual details. Important caveate: Missing values can bias the results of studies
  • 29. (sometimes severely). If you have a significant amount of missing data, it is probably a good idea to consult a statistician or data scientist before deleting cases or imputing missing values. https://www.jstatsoft.org/article/view/v074i07/v74i07.pdf https://www.jstatsoft.org/article/view/v074i07/v74i07.pdf 18 CHAPTER 1. DATA PREPARATION Chapter 2 Introduction to ggplot2 This section provides an brief overview of how the ggplot2 package works. If you are simply seeking code to make a specific type of graph, feel free to skip this section. However, the material can help you understand how the pieces fit together. 2.1 A worked example The functions in the ggplot2 package build up a graph in layers. We’ll build a a complex graph by starting with a simple graph and adding additional elements, one at a time. The example uses data from the 1985 Current Population Survey to explore the relationship between wages (wage) and experience (expr). # load data data(CPS85 , package = "mosaicData")
  • 30. In building a ggplot2 graph, only the first two functions described below are required. The other functions are optional and can appear in any order. 2.1.1 ggplot The first function in building a graph is the ggplot function. It specifies the • data frame containing the data to be plotted • the mapping of the variables to visual properties of the graph. The mappings are placed within the aes function (where aes stands for aesthetics). # specify dataset and mapping library(ggplot2) ggplot(data = CPS85, mapping = aes(x = exper, y = wage)) Why is the graph empty? We specified that the exper variable should be mapped to the x-axis and that the wage should be mapped to the y-axis, but we haven’t yet specified what we wanted placed on the graph. 19 https://ggplot2.tidyverse.org/ 20 CHAPTER 2. INTRODUCTION TO GGPLOT2 0
  • 31. 10 20 30 40 0 20 40 exper w a g e Figure 2.1: Map variables 2.1. A WORKED EXAMPLE 21 2.1.2 geoms Geoms are the geometric objects (points, lines, bars, etc.) that can be placed on a graph. They are added using functions that start with geom_. In this example, we’ll add points using the geom_point function, creating a scatterplot. In ggplot2 graphs, functions are chained together using the + sign to build a final plot. # add points
  • 32. ggplot(data = CPS85, mapping = aes(x = exper, y = wage)) + geom_point() 0 10 20 30 40 0 20 40 exper w a g e The graph indicates that there is an outlier. One individual has a wage much higher than the rest. We’ll delete this case before continuing. # delete outlier library(dplyr) plotdata <- filter(CPS85, wage < 40) # redraw scatterplot ggplot(data = plotdata,
  • 33. mapping = aes(x = exper, y = wage)) + geom_point() A number of parameters (options) can be specified in a geom_ function. Options for the geom_point function include color, size, and alpha. These control the point color, size, and transparency, respectively. Trans- 22 CHAPTER 2. INTRODUCTION TO GGPLOT2 0 10 20 0 20 40 exper w a g e Figure 2.2: Remove outlier 2.1. A WORKED EXAMPLE 23 0
  • 34. 10 20 0 20 40 exper w a g e Figure 2.3: Modify point color, transparency, and size parency ranges from 0 (completely transparent) to 1 (completely opaque). Adding a degree of transparency can help visualize overlapping points. # make points blue, larger, and semi-transparent ggplot(data = plotdata, mapping = aes(x = exper, y = wage)) + geom_point(color = "cornflowerblue", alpha = .7, size = 3) Next, let’s add a line of best fit. We can do this with the geom_smooth function. Options control the type of line (linear, quadratic, nonparametric), the thickness of the line, the line’s color, and the presence or absence of a confidence interval. Here we request a linear regression (method = lm) line (where lm stands for linear model).
  • 35. # add a line of best fit. ggplot(data = plotdata, mapping = aes(x = exper, y = wage)) + geom_point(color = "cornflowerblue", alpha = .7, size = 3) + geom_smooth(method = "lm") Wages appears to increase with experience. 24 CHAPTER 2. INTRODUCTION TO GGPLOT2 0 10 20 0 20 40 exper w a g e Figure 2.4: Add line of best fit
  • 36. 2.1. A WORKED EXAMPLE 25 2.1.3 grouping In addition to mapping variables to the x and y axes, variables can be mapped to the color, shape, size, transparency, and other visual characteristics of geometric objects. This allows groups of observations to be superimposed in a single graph. Let’s add sex to the plot and represent it by color. # indicate sex using color ggplot(data = plotdata, mapping = aes(x = exper, y = wage, color = sex)) + geom_point(alpha = .7, size = 3) + geom_smooth(method = "lm", se = FALSE, size = 1.5) 0 10 20 0 20 40
  • 37. exper w a g e sex F M The color = sex option is placed in the aes function, becaus e we are mapping a variable to an aesthetic. The geom_smooth option (se = FALSE) was added to suppresses the confidence intervals. It appears that men tend to make more money than women. Additionally, there may be a stronger relation- ship between experience and wages for men than than for women. 26 CHAPTER 2. INTRODUCTION TO GGPLOT2 $0 $5 $10 $15
  • 38. $20 $25 0 10 20 30 40 50 exper w a g e sex F M Figure 2.5: Change colors and axis labels 2.1.4 scales Scales control how variables are mapped to the visual characteristics of the plot. Scale functions (which start with scale_) allow you to modify this mapping. In the next plot, we’ll change the x and y axis scaling, and the colors employed. # modify the x and y axes and specify the colors to be used ggplot(data = plotdata, mapping = aes(x = exper, y = wage, color = sex)) +
  • 39. geom_point(alpha = .7, size = 3) + geom_smooth(method = "lm", se = FALSE, size = … Patient Case #3 Patient: Rashid Ahmed Diagnosis: Dehydration and hypokalemia Brief Summary: Rashid Ahmed is a 50-year-old Middle Eastern male who was admitted this morning to the medical unit with a diagnosis of dehydration and hypokalemia. He has been experiencing nausea, vomiting, and diarrhea for the past 48 hours after eating at a local restaurant three days ago. Medications: · Trimethoprim/Sulfamethoxazole 160/800 mg PO q12h · Potassium chloride (KCL) 40 mEq PO once · Ondansetron 4 mg IV push q6h prn for nausea · Lisinopril 5mg PO daily · Atorvastatin 10mg PO nightly Orders: · Vital signs every 4 hours and prn · Daily weights · Activity: Up ad lib with assistance x1 · Diet: Clear liquids, progress to regular as tolerated · IV: 1000 mL dextrose 5% in normal saline with 20 mEq KCL at 125 mL/hr · Intake and output, record every 8 hours SBAR Report: S: Mr. Rashid Ahmed is a 50-year-old Middle Eastern male who was admitted to our unit at 0600 this morning after being admitted to the ED at 0400 with a diagnosis of dehydration and
  • 40. hypokalemia. We are monitoring his fluid and electrolyte status closely. I have just received admission orders. B: Three days ago, he developed abdominal cramping, nausea, vomiting, and severe diarrhea 12 hours after eating lunch at a local restaurant. The symptoms have continued for the past 2 days, and food and fluid intake has been minimal to none since the symptoms began. Last night he nearly passed out while going to the bathroom around 0300. Mr. Ahmed was brought to the ED by his wife, and reported dizziness, weakness, and continued nausea. He received 4 mg ondansetron IV for nausea in the ED. Lab work was drawn and is available in the patient chart, and urine and stool samples have been sent to the lab. Mr. Ahmed’s only medical history includes hypertension and hyperlipidemia. A: Mr. Ahmed is drowsy but oriented x 3, appears ill, and is irritable. He reports having a headache, which he rates a 4 on a scale of 0–10, but he hasn't wanted anything for it. Admission weight was 73 kg (162 lb), which the patient reports to be about 4.5 kg (10 lb) less than usual. Vital signs were obtained on admission, including orthostatic blood pressure readings which were positive. Patient had drop in BP from 135/70 while lying down to 105/55 once he stood up. He reports dizziness. Heart rate is tachycardic and irregular. Patient also noted to have a 100.4 degree temperature. He has only taken a few ice chips since admission due to his nausea. The patient had one small liquid stool in the ER. He has not voided or experienced emesis since admission. An IV bolus has been completed and now D5NS IV fluids are running at 125 mL/hr. R: Mr. Ahmed has new IV orders that need to be initiated. You will need to start him on oral antibiotics and potassium when nausea resolves. Provide patient education on safety, his prescribed medications, and intake and output measurement. Patient Case Scenario #1 Chris Parrish
  • 41. Patient: Christopher Parrish Diagnosis: Cystic fibrosis, weight loss, and fatigue Brief Summary: Christopher Parrish is an 18-year-old adolescent male who is hospitalized for management of cystic fibrosis with weakness and weight loss. He reports fatigue, and he has had a recent 6 kg (13.2 lb) weight loss. Hewas diagnosed with cystic fibrosis as an infant and has had multiple hospitalizations for respiratory and nutritional support. A nasogastric (NG) tube has been placed for feedings. Medications: · Pancrelipase supplement 5 capsules PO QID with meals and at start of nightly tube feeding · Multivitamin 2 tabs PO daily · Potassium chloride 40 mEq PO daily Orders: · Vital signs every 4 hours · Daily intake and output, and weight · Chest X-ray: AP and lateral tomorrow morning · Insert nasogastric tube · Nutrition consult · Diet: High-fat, high-calorie, high-protein regular diet, supplement with high-protein snacks in between meals · Promote tube feedings (1.5 kcal/mL) in nasogastric tube; administer 720 kcal over 8 hours at night (infuse via pump from 2200-0600) SBAR: S: Christopher Parrish is an 19-year-old male who was admitted at 1900 today. His mother visited him at his college dormitory and was very concerned with his health; he seemed weak and had lost weight since she last saw him. She took him to see his primary care provider, and the provider admitted him and has ordered a tube feeding. An 8-French, 42-inch feeding tube was
  • 42. placed in his right nare about an hour ago, and x-ray just called and confirmed placement in the stomach. The pump is in his room. He is up to the bathroom prn; otherwise bed rest. B: Christopher was diagnosed with cystic fibrosis as a child and has had frequent hospitalizations previously. He reports fatigue and has recently lost 6 kg (13.2 lb) after he registered at the local college and moved to live in a dormitory, one month ago. Chris's mom was here earlier, but she is a single parent and has two younger boys, so she had to go home. A: Christopher is awake and alert. His heart rate and rhythm are regular at 85 bpm. Breath sounds are fine with a respiratory rate at 18/min and his SpO2 saturation is 98% on room air. His color is a bit pale. Blood pressure is 118/78 mm Hg. He reports no pain and states he's not had much appetite the past few weeks. His skin turgor is > 3 seconds and his mucous membranes are dry. His belly is flat and nontender. Bowel sounds are normoactive. Chris is noted to have a persistent productive cough, and his sputum is noted to be thick and yellow in color. Chris tends to get short of breath with any strenuous activity. He was noted to become short of breath, with an increase in RR to 26 bpm, after walking in the hallway for about 10 minutes. His potassium level this morning was low at 3.2 mEq/L. R: Christopher is due for vital signs and assessment. The tube feeding just arrived, and you will need to start it on the pump. He needs 720 kilocalories over 8 hours overnight. His regular diet is high calorie, high fat, but he wasn't too hungry this evening; just had a bit of his chocolate shake. You will need to give his pancreatic enzymes orally before you start the tube feeding. You should also assess his diet and reinforce patient education on nutrition. NRG5000 Theoretical Foundations of Nursing Dr. Lisa Capps, Faculty 1
  • 43. Concept Map and Care Plan (Clinical Assignment #2) Grading Rubric Student Name: __________________________________________________ Description Points Received/ Total Points Possible Comments Diagnosis #1 Diagnosis #2 Totals Patient Information and Health Assessments · Complete patient demographics, health assessments, and interventions ____/ 3 Pharmacology: · Complete& accurate description of current meds, including purpose for this patient, side effects, and all other data listed in chart ____/ 3 Pathophysiology: · Includes “signs and symptoms” · Includes APA references cited
  • 44. ____/ 3 Nursing Diagnosis (Include ALL 2 Dx): · Reflects the primary diagnosis · Appropriate for patient scenario as well as priority level · In acceptable NANDA format · Includes all parts stem, R/T, AEB · Only 1 ‘Risk For’ diagnosis can be used ____/ 3 Provided 2 nursing diagnoses: 2 points per diagnosis ____/ 4 Assessment: · Appropriate for chosen diagnosis · Includes objective & subjective historical support diagnosing data ____/3 + ____/3 = ____/ 6 Patient Outcomes: · Include at least 2 outcomes for each diagnosis · Specific to the patient diagnosis · Contains the following 4 criteria: measurable, attainable, realistic, and timed · All criteria present for patient’s expected outcome ____/3 + ____/3
  • 45. = ____/ 6 Intervention/Implementation: · Include at least 3 nursing interventions for each patient outcome · Includes interventions/ nursing actions directly relating to pt. outcomes · Specific in action, frequency and contain rationale · # of interventions is appropriate to help pt./ family meet their outcomes ____/3 + ____/3 = ____/ 6 Evaluation: · Must have an evaluation statement written for each patient outcome · Includes all data that is listed as criteria in outcomes · Outcomes are determined to be met, partially met, or not met · If outcome was not met/ partially met, plan of care is revised/ continued & new evaluation date/time is set ____/3 + ____/3 = ____/ 6 Total Points: ____/ 40 Patient Case #2 Patient: Edith Jacobson Diagnosis: Left hip fracture Brief Summary:
  • 46. Edith Jacobson is an 85-year-old white female with a history of osteoporosis. She lives at home by herself where she fell and broke her left hip yesterday evening, after having complaints of dizziness, weakness, and fatigue. She is scheduled to have surgery in 2 days. Medications: · Enoxaparin sodium 40 mg SQ daily · Docusate sodium 100 mg PO daily · Morphine sulfate 4 mg IV q4h prn for pain · Metoprolol 25 mg PO BID · Furosemide 20mg PO daily Orders: · Vital signs every 4 hours · Activity: Bed rest · Anti-embolism stockings on both legs (knee-length) SBAR Report: S: Mrs. Jacobson is an 85-year-old white female who was admitted last evening after falling and fracturing her hip. X-rays have been taken and show left intertrochanteric hip fracture. Mrs. Jacobson is scheduled for surgery in 2 days. B: Mrs. Jacobson has a 10-year history of osteoporosis and was newly diagnosed with congestive heart failure last year. Her daughter reports that recently Mrs. Jacobson has been having dizzy spells, fatigue, and weakness. Mrs. Jacobson lives alone and is usually able to perform all her ADLs independently. She does have a cane at home but often times refuses to use it because she “doesn’t think she needs it”. Mrs. Jacobson is usually pretty active, but has been much more sedentary lately due to increasing weakness and fatigue due to medication non- compliance with her heart failure medications. A: Mrs. Jacobson is AOx4 and her vital signs are stable. Her pain level is currently a 7 out of 10, and she describes is as “throbbing and aching” in her left hip. Often times Mrs. Jacobson will moan or cry out in pain, especially whenever she
  • 47. needs to be moved in bed. She is very resistant to let anyone touch or move her left leg. The skin is intact; color and sensation around the hip area are within normal limits. A Morse Fall Scale assessment was completed on admission, and her score was 45. Fall precautions were implemented. Mrs. Jacobson has limited ROM in her left hip and her muscle strength in her left lower extremity is weak at a 2/5. Mrs. Jacobson has been having some episodes of urinary and bowel incontinence since being admitted to the hospital. She frequently needs to be reminded that she cannot get out of bed due to her activity restriction. R: You will need to reposition Mrs. Jacobson as she needs to be turned every 2 hours. You should perform a focused musculoskeletal assessment, reinforce safety, and provide patient education on fall risk. Assess her pain level and medicate for pain if needed. Patient Case #4 Patient: Vernon Russell Diagnosis: Right-sided stroke (mild left hemiplegia) Brief Summary: Vernon Russell is a 55-year-old Native American male who was admitted with a stroke with mild left hemiplegia yesterday. The patient is nothing by mouth except medications. Chest-x-ray confirmed possible aspiration pneumonia on the right side. Medications: · Losartan 50 mg PO BID · Aspirin 81 mg PO daily · Metformin 500 mg PO BID · Chlorthalidone 25 mg PO daily Orders: · Vital signs and neuro checks every 4 hours · Activity: Up to chair, up to the bathroom with assistance · Nothing by mouth except medications until swallow study
  • 48. completed tomorrow · Speech therapist swallow study · Fall risk assessment · Labs: CBC, chemistry panel, and prothrombin time · Bedside blood glucose twice a day SBAR Report: S: Mr. Russell is a 55-year-old Native American male who was admitted with a stroke with mild left hemiplegia yesterday afternoon. He had a head CT and received thrombolytic therapy in the ED. He is nothing by mouth except for medications until the speech therapist has completed a video swallow study, which is scheduled for later this morning. He is scheduled for physical therapy later today. B: Mr. Russell has a history of hypertension, coronary artery disease, and diabetes mellitus type 2. He has smoked over a pack of cigarettes per day for the past 35 years and does not exercise. A: We have already checked his blood glucose level this morning. His vital signs have been stable and he slept well last night. He was able to get up to go to the bathroom with the use of a walker. His neurological checks are stable and he continues to have mild left hemiplegia. His hand grasps are almost equal but a little weaker on the left side. His pupils are equal and react to light. Swallow reflex is intact but impaired. He is oriented x2. Patient is slow to respond and noted to have some periods of slurred or delayed speech. I have already done a Morse Fall Risk assessment with a total high risk score of 60. Fall precautions implemented. Upon bedside RN swallow evaluation, the patient was noted to have frequent coughing when given a small sip of water. Chest x-ray done in the ED reveals that the patient has right-sided pneumonia, possibly due to aspiration. R: You should do a vital signs assessment, perform a neurological assessment, and talk about safety with Mr. Russell. His morning medications are up and should be administered with caution. Maintain NPO status until video swallow
  • 49. performed. Patient was able to stand on side of bed with physical therapist, but weakness noted. Patient unable to take steps. Continue fall and aspiration precautions.