variable <- value
The padr
package was designed to prepare datetime data for analysis. That is, to take raw, timestamped data, and quickly convert it into a tidy format that can be analyzed with all the tidyverse tools. Recently, a colleague and I discovered a second use for the package that I had not anticipated: checking data quality. Every analysis should contain checking if data are as expected. In the case of timestamped data, observations are sometimes missing due to technical malfunction of the system that produced them. Here are two examples that show how pad
and thicken
can be leveraged to detect problems in timestamped data quickly.
Lets imagine our system produces a value every five minutes. We want to analyse the data of the last couple of months and start by some routine checks. We quickly find that the number of records is not what we expected.
library(tidyverse)
library(padr)
regular_system %>% head
## # A tibble: 6 x 2
## timestamp value
##
## 1 2017-03-01 00:00:00 423.69
## 2 2017-03-01 00:05:00 434.51
## 3 2017-03-01 00:10:00 206.01
## 4 2017-03-01 00:15:00 432.83
## 5 2017-03-01 00:20:00 220.07
## 6 2017-03-01 00:25:00 393.44
seq(regular_system$timestamp %>% min, regular_system$timestamp %>% max,
by = "5 min") %>% length()
## [1] 32456
nrow(regular_system)
## [1] 32454
Two observations are missing here, with pad
they are located in no time.
regular_system %>%
mutate(check_var = 1) %>%
pad() %>%
filter(is.na(check_var))
## pad applied on the interval: 5 min
## # A tibble: 2 x 3
## timestamp value check_var
##
## 1 2017-06-08 11:55:00 NA NA
## 2 2017-06-08 12:00:00 NA NA
There we are, aparrantly the system took a lunch break on June the 8th.
Now a more common situation. The system only produces data when it has something to tell us. This makes the observations irregular. This server produces a message each time some event happened.
irregular_system %>% head
## # A tibble: 6 x 2
## time_stamp message
##
## 1 2016-10-09 00:02:01 QL2341@
## 2 2016-10-09 00:07:01 #A222IWL
## 3 2016-10-09 00:11:01 QL2341@
## 4 2016-10-09 00:17:00 WW#5
## 5 2016-10-09 00:17:00 QL2341@
## 6 2016-10-09 00:17:01 WW#5
Also here are server might be temporarily down, however, this is not so easy to locate. It is helpful here to apply thicken
, then aggregate, pad, and fill, and finally plot the result. We might want to look at several different interval, lets make it as generic as possible.
thicken_plot <- function(x, interval) {
x %>% thicken(interval, "ts_thick") %>%
count(ts_thick) %>%
pad() %>%
fill_by_value() %>%
ggplot(aes(ts_thick, n)) +
geom_line()
}
Lets look at 10 minute intervals.
thicken_plot(irregular_system, "10 min")
## pad applied on the interval: 10 min
Thats not too helpful, maybe a little coarser.
thicken_plot(irregular_system, "30 min")
## pad applied on the interval: 30 min
Now we see a dip at the middle of the day for October 10th, where for all the other days there is ample activty during these hours. There must be something wrong here that has to be sorted out. That will wrap up these two quick examples of how to use padr
for data quality checking.
I will present the package during a lightning talk at useR next week (Wednesday 5:50 pm at 4.02 Wild Gallery). Hope to meet many of you during the conference!
Since about October last year, I’ve been writing an introduction to R book. It’s
been quite the experience. I’ve finally started making time to document some of
the interesting things I’ve learned (about R, about writing, about how to
bring those two together) along the way.
The book is aimed at proper beginners; people with absolutely no formal coding
experience. This tends to mean people coming from Excel who need to do more than
a spreadsheet can/should.
I'm writing an R book for real beginners (ppl with 0 code XP) via @ManningBooks! What tripped you up most when you first learned R? Pls RT!
— Jonathan Carroll (@carroll_jono) September 27, 2016
Most of the books I’ve looked at which claim to teach programming begin with
some strong assumptions about the reader already knowing how to program, and
teach the specific syntax of some language. That’s no good if this is your first
language, so I’m working towards teaching the concepts, the language, and the
syntax (warts and all).
The book is currently available under the Manning Early Access Program (MEAP)
which means if you buy it you get the draft of the first three chapters right
now. If you find something you still don’t understand, or you don’t like how
I’ve written some/all of it, then jump onto the forum and let me know. I make
more edits and write more chapters, and you get updated versions. Lather, rinse,
repeat until the final version and you get a polished book which (if I’m any
good) contains what you want it to.
I’m genuinely interested in getting this right; I want to help people learn R. I
contribute a bit of time on Stack Overflow answering people’s questions, and
it’s very common to see questions that shouldn’t need asking. I don’t blame the
user for not knowing something (a different answer for not searching, perhaps),
but I can help make the resource they need.
Chapter 1 is a free download, so please check that out too! At the moment the
MEAP covers the first three chapters, but the following four aren’t too far
behind.
I’ll document some of the behind-the-scenes process shortly, but for now here’s
an excerpt from chapter 2:
In order to do something with our data, we will need to tell R
what to call
it, so that we can refer to it in our code. In programming in general, we
typically have variables (things that may vary) and values (our data). We’ve
already seen that different data values can have different types, but we
haven’t told R
to store any of them yet. Next, we’ll create some variables
to store our data values.
If we have the values 4
and 8
and we want to do something with them, we can
use the values literally (say, add them together as 4 + 8
). You may be
familiar with this if you frequently use Excel; data values are stored in cells
(groups of which you can opt to name) and you tell the program which values you
wish to combine in some calculation by selecting the cells with the mouse or
keyboard. Alternatively, you can opt to refer to cells by their grid reference
(e.g. A1
). Similarly to this second method, we can store values in variables
(things that may vary) and abstract away the values. In R
, assigning of
values to variables takes the following form
variable <- value
The assignment operator <-
can be thought of as storing the value/thing on
the right hand side into the name/thing on the left hand side. For example, try
typing x <- 4
into the R
Console
then press Enter:
x
has been assigned the value 4
.You could just as easily use the equals sign to achieve this; x = 4
but I
recommend you use <-
for this for reasons that will become clear later.
You’ll notice that the Environment
tab of the Workspace
pane now lists
x
under Values
and shows the number 4 next to it, as shown in [fig-x_eq_4]
x
has been assigned the value 4
.What happened behind the scenes was that when we pressed Enter, R
took
the entire expression that we entered (x <- 4
) and evaluated it. Since we
told R
to assign the value 4
to the variable x
, R
converted the value
4
to binary and placed that in the computer’s memory. R
then gives us a
reference to that place in the computer’s memory and labels it x
. A diagram of
this process is shown in [fig-assign] Nothing else appeared in the
Console
because the action of assigning a value doesn’t return anything
(we’ll cover this more in our section on functions).
This is overly simplified, of course. Technically speaking, in R
, names have
objects rather than the other way around. This means that R
can be quite
memory efficient since it doesn’t create a copy of anything it doesn’t need to.
On “hidden” variables
Variables which begin with a period (e.g. |
We can retrieve the value assigned to the variable x
by asking R
to print
the value of x
print(x = x)
#> [1] 4
for which we have a useful shortcut — if your entire expression is just a
variable, R
will assume you mean to print()
it, so
x
#> [1] 4
works just the same.
Now, about that [1]
: it’s important to know that in R
, there’s no such thing
as a single value; every value is actually a vector of values (we’ll cover
these properly in the next chapter, but think of these as collections of values
of the same type).^{[1]}
Whenever R
prints a value it allows for the case where the value contains more
than one number. To make this easier on the eye, it labels the first value
appearing on the line by it’s position in the collection. For collections
(vectors) with just a single value, this might appear strange, but this makes
more sense once our variables contain more values
# Print the column names of the mtcars dataset
names(x = mtcars)
#> [1] "mpg" "cyl" "disp" "hp" "drat" "wt" "qsec" "vs" "am" "gear" #> [11] "carb"
We can assign another variable to another value
y <- 8
There are few restrictions for what we can name our data values, but R
will
complain if you try to break them. Variables should start with a letter, not a
number. Trying to create the variable 2b
will generate an error. Variables can
also start with a dot (.
) as long as it’s not immediately followed by a
number, although you may wish to avoid doing so. The rest of the variable name
can consist of letters (upper and lower case) and numbers, but not punctuation
(except .
or _
) or other symbols (except the dot, though again, preferably
not).
There are also certain reserved words that you can’t name variables as. Some
are reserved for built-in functions or keywords
if
, else
, repeat
, while
, function
, for
, in
, next
, and break
.
Others are reserved for particular values
TRUE
, FALSE
, NULL
, Inf
, NaN
, NA
, NA_integer_
, NA_real_
,
NA_complex_
, and NA_character_
.
We’ll come back to what each of these means, but for now you just need to know
that you can’t create a variable with one of those names.
On overwriting names
What you can do however, which you may wish to take care with, is overwrite If you were translating an equation into code, and wanted to enter the value The default value can still be accessed by specifying the package in which it is
#> [1] 3.141593
This is also an issue for functions, with the same solution; specify the package |
We’ll cover how to do things to our variables in more detail in the next
section, but for now let’s see what happens if we add our variables x
and y
in the same way as we did for our regular numbers
x + y
#> [1] 12
which is what we got when we added these numbers explicitly. Note that since our
expression produces just a number (no assignment), the value is printed. We’ll
cover how to add and subtract values in more depth in our section on basic mathematics.
R
has no problems with overwriting these values, and it doesn’t mind what data
you overwrite these with.^{[2]}
y <- 'banana'
y
#> [1] "banana"
R
is case-sensitive, which means that it treats a
and A
as distinct
names. You can have a variable named myVariable
and another named MYvariable
and another named myVARIABLE
and R
will hold the value assigned to each
independently.
There are only two hard things in Computer Science: cache invalidation and naming things.
I said earlier that R
won’t keep track of your units so it’s a good idea to
name your variables in a way that makes logical sense, is meaningful, and will
help you remember what it represents. Variables x
and y
are fine for playing
around with values, but aren’t particularly meaningful if your data represents
speeds, where you may want to use something like speed_kmph
for speeds in
kilometers per hour. Underscores (_
) are allowed in variable names, but
whether or not you use them is up to you. Some programmers prefer to name
variables in this way (sometimes referred to as ‘snake_case’), others prefer
‘CamelCase’. The use of periods (dots, .
) to separate words is discouraged for
reasons beyond the scope of this book.^{[3]}
Naming things
Be careful when naming your variables. Make them meaningful and |
If you’re familiar with working with data in a spreadsheet program (such as
Excel), you may expect your variables to behave in a way that they
won’t. Automatic recalculation is a very useful feature of spreadsheet programs,
but it’s not how R
behaves.
If we assign our two variables, then add them, we can save that result to
another variable
a <- 4
b <- 8
sum_of_a_and_b <- a + b
This has the value we expect
print(x = sum_of_a_and_b)
#> [1] 12
Now, if we change one of these values
b <- 2
this has no impact on the value of the variable we created to hold the sum
earlier
print(x = sum_of_a_and_b)
#> [1] 12
Once the sum was calculated, and that value stored in a variable, the connection
to the original values was lost. This makes things reliable because you know
for sure what value a variable will have at any point in your calculation by
following the steps that lead to it, whereas a spreadsheet depends much more on
its current overall state.
<-
vs =
)If you’ve read some R
code already, you’ve possibly seen that both <-
and
=
are used to assign values to objects, and this tends to cause some
confusion. Technically, R
will accept either when assigning variables, so in
that respect it comes down to a matter of style (I still highly recommend
assigning with <-
). The big difference comes when using functions that take
arguments — there you should only use =
to specify what the value of the
argument. For example, when we inspected the mtcars
data, we could
specify a string with which to indent the output
str(object = mtcars, indent.str = '>> ')
#> 'data.frame': 32 obs. of 11 variables: #> >> $ mpg : num 21 21 22.8 21.4 18.7 18.1 14.3 24.4 22.8 19.2 ... #> >> $ cyl : num 6 6 4 6 8 6 8 4 4 6 ... #> >> $ disp: num 160 160 108 258 360 ... #> >> $ hp : num 110 110 93 110 175 105 245 62 95 123 ... #> >> $ drat: num 3.9 3.9 3.85 3.08 3.15 2.76 3.21 3.69 3.92 3.92 ... #> >> $ wt : num 2.62 2.88 2.32 3.21 3.44 ... #> >> $ qsec: num 16.5 17 18.6 19.4 17 ... #> >> $ vs : num 0 0 1 1 0 1 0 1 1 1 ... #> >> $ am : num 1 1 1 0 0 0 0 0 0 0 ... #> >> $ gear: num 4 4 4 3 3 3 3 4 4 4 ... #> >> $ carb: num 4 4 1 1 2 1 4 2 2 4 ...
If we had used <-
instead of =
for either argument, then R
would treat
that as creating a new variable object
or indent.str
with value mtcars
or
'>> '
respectively, which isn’t what we want.
Assigning to variables.
#> [1] 4.8
#> num 4.8
#> [1] "banana"
#> chr "banana" |
Note that we didn’t need to tell R
that one of these was a number and one was
a string, it figured that out itself. It’s good practice (and easier to read) to
make your <-
line up vertically when defining several variables:
first_name <- 'John'
last_name <- 'Smith'
top_points <- 23
but only if this can be achieved without adding too many spaces (exactly how
many is too many is up to you).
Watch this space!
An extra space can make a big difference to the syntax. Compare:
with
#> [1] FALSE In the first case we assigned the value |
Now that we know how to provide some data to R
, what if we want to explicitly
tell R
that our data should be of a specific type, or we want to convert our
data to a different type? That’s an article for another day.
R
has no scalar types.
R
to denote functions acting on a specific class, such as print.Date()
.
ggplot2
extension, geofacet
, that supports arranging facet panels that mimics geographic topoloty.
After playing with it, I realized that it is not only for visualizing geo
-related data, but also can be fun for presenting data to mimics pixel art.
Here is an example using the Turkey shape:
Turkey <- read.csv("http://pages.iu.edu/~cdesante/turkey.csv")
Turkey = Turkey[, -3]
colnames(Turkey)[2:1] = c("row", "col")
Turkey$row = max(Turkey$row) - Turkey$row +1
Turkey$name <- Turkey$code <- paste0('turkey', 1:nrow(Turkey))
require(ggplot2)
require(geofacet)
x <- split(eu_gdp, eu_gdp$code)
x <- x[sample.int(length(x), nrow(Turkey), replace=T)]
for (i in 1:length(x)) {
x[[i]]$code = Turkey$code[i]
}
y <- do.call(rbind, x)
p1 <- ggplot(y, aes(gdp_pc, year))+ geom_line(color="steelblue") +
facet_geo(~code, grid=Turkey, scales='free')
print(p1)
p1 + theme_void() + theme(strip.text.x = element_blank())
]]>I just discovered an interesting ggplot2
extension, geofacet
, that supports arranging facet panels that mimics geographic topoloty.
After playing with it, I realized that it is not only for visualizing geo
-related data, but also can be fun for presenting data to mimics pixel art.
Here is an example using the Turkey shape:
Turkey <- read.csv("http://pages.iu.edu/~cdesante/turkey.csv")
Turkey = Turkey[, -3]
colnames(Turkey)[2:1] = c("row", "col")
Turkey$row = max(Turkey$row) - Turkey$row +1
Turkey$name <- Turkey$code <- paste0('turkey', 1:nrow(Turkey))
require(ggplot2)
require(geofacet)
x <- split(eu_gdp, eu_gdp$code)
x <- x[sample.int(length(x), nrow(Turkey), replace=T)]
for (i in 1:length(x)) {
x[[i]]$code = Turkey$code[i]
}
y <- do.call(rbind, x)
p1 <- ggplot(y, aes(gdp_pc, year))+ geom_line(color="steelblue") +
facet_geo(~code, grid=Turkey, scales='free')
print(p1)
p1 + theme_void() + theme(strip.text.x = element_blank())
The importFile() function in H2O is extremely efficient due to the parallel reading. The benchmark comparison below shows that it is comparable to the read.df() in SparkR and significantly faster than the generic read.csv().
library(SparkR, lib.loc = paste(Sys.getenv("SPARK_HOME"), "/R/lib", sep = "")) sc <- sparkR.session(master = "local", sparkConfig = list(spark.driver.memory = "10g", spark.driver.cores = "4")) library(h2o) h2o.init(max_mem_size = "10g") library(rbenchmark) benchmark(replications = 5, order = "elapsed", relative = "elapsed", csv = { df <- read.csv("Documents/nycflights13.csv") print(nrow(df)) rm(df) }, spk = { df <- read.df("Documents/nycflights13.csv", source = "csv", header = "true", inferSchema = "true") print(nrow(df)) rm(df) }, h2o = { df <- h2o.importFile(path = "Documents/nycflights13.csv", header = TRUE, sep = ",") print(nrow(df)) rm(df) } ) # test replications elapsed relative user.self sys.self user.child sys.child # 3 h2o 5 8.221 1.000 0.508 0.032 0 0 # 2 spk 5 9.822 1.195 0.008 0.004 0 0 # 1 csv 5 16.595 2.019 16.420 0.176 0 0
Supplementary notes for CJ Brown’s talks on dataviz in 2017 for Griffith
University’s honours students and the UQ Winterschool in
Bioinformatics.
I picked this example to demonstrate a simple barchart for representing
the sizes of different things.
mnsize <- c(2800, 650)
sesize <- c(800, 50)
nams <- c('Male', 'Female')
cols <- c('steelblue', 'sienna3')
par(oma = c(1,2,1,1), mgp = c(6,1,0), mar = c(5,8,4,2))
barplot(mnsize, names.arg = '', las = 1, ylab = 'Weight (kg)', cex.axis = 2, cex.lab =2, col = cols)
legend('topright', legend = nams, pch = 15, col = cols, cex = 2)
Compare these. Note that if we compare circles we should use area, not
the radius or diameter to scale their size.
n <- c(10, 5)
barplot(n, col = 'skyblue', xaxt = 'n', yaxt = 'n')
rad1 <- 1
area1 <- pi*(rad1^2)
area2 <- area1/2
rad2 <- sqrt(area2/pi)
par(mfrow = c(1,2), mar = c(0,0,0,0))
pie(1, col = 'skyblue', labels = NA, border = NA, radius = rad1)
pie(1, col = 'skyblue', labels = NA, border = NA, radius = rad2)
Let’s create a point cloud to demonstrate some data exploration
techniques
set.seed(42)
x <- rnorm(1000)
y <- 5*x + 3 + rnorm(1000, sd = 15)
plot(x,y, pch = 16, col = grey(0.5,0.5), las = 1)
Can’t see alot here. A linear model might help us explore if there is
any trend going on:
mod1 <- lm(y ~ x)
plot(x,y, pch = 16, col = grey(0.5,0.5), las = 1)
abline(mod1, lwd = 2, col = 'red')
xnew <- seq(min(x), max(x), length.out = 100)
pmod <- predict(mod1, newdata =data.frame(x=xnew), se = T)
lines(xnew, pmod$fit + pmod$se.fit, lwd = 2, col = 'red', lty = 2)
lines(xnew, pmod$fit - pmod$se.fit, lwd = 2, col = 'red', lty = 2)
What about identifying extreme points, that may be worth investigating
further? We can pick out points that are greater than 2SDs from the
trend:
modresid <- resid(mod1)
sd2 <- sd(modresid)*2
ipt <- which(abs(modresid) > sd2)
plot(x,y, pch = 16, col = grey(0.5,0.5), las = 1)
abline(mod1, lwd = 2, col = 'red')
points(x[ipt], y[ipt], pch = 16, col = rgb(1,0,0, 0.6))
Each of these graphs of the same data has a slightly different
interpretation.
x <- 1:100
y <- x + rnorm(100, sd=30)
plot(x,y, pch = 16, col = grey(0.5, 0.5))
mod1 <- lm(y ~ x)
plot(x,y, col = 'white')
abline(mod1, lwd = 3, col = 'red')
library(MASS)
filled.contour(kde2d(x,y), scale = F)
plot(x,y, pch = 16, col = grey(0.5, 0.5))
abline(mod1, lwd = 3, col = 'red')
The datasaurus is a great example of why you should view your data,
invented by Alberto Cairo. See Steph Locke’s code and package on
github for making this in R.
library(datasauRus)
datnames <- rev(unique(datasaurus_dozen$dataset))
nlevels <- length(datnames)
for (i in 1:nlevels){
i <- which(datasaurus_dozen$dataset == datnames[i])
plot(datasaurus_dozen$x[i], datasaurus_dozen$y[i],
xlab = "x", ylab = "y", las = 1)
Sys.sleep(1)
}
Convince yourself that the mean, sd and correlation is the same in all
of these plots:
library(dplyr)
datasaurus_dozen %>% group_by(dataset) %>%
summarize(meanx = mean(x), meany = mean(y),
sdx = sd(x), sdy = sd(y),
corr = cor(x,y))
## # A tibble: 13 × 6
## dataset meanx meany sdx sdy corr
##
## 1 away 54.26610 47.83472 16.76982 26.93974 -0.06412835
## 2 bullseye 54.26873 47.83082 16.76924 26.93573 -0.06858639
## 3 circle 54.26732 47.83772 16.76001 26.93004 -0.06834336
## 4 dino 54.26327 47.83225 16.76514 26.93540 -0.06447185
## 5 dots 54.26030 47.83983 16.76774 26.93019 -0.06034144
## 6 h_lines 54.26144 47.83025 16.76590 26.93988 -0.06171484
## 7 high_lines 54.26881 47.83545 16.76670 26.94000 -0.06850422
## 8 slant_down 54.26785 47.83590 16.76676 26.93610 -0.06897974
## 9 slant_up 54.26588 47.83150 16.76885 26.93861 -0.06860921
## 10 star 54.26734 47.83955 16.76896 26.93027 -0.06296110
## 11 v_lines 54.26993 47.83699 16.76996 26.93768 -0.06944557
## 12 wide_lines 54.26692 47.83160 16.77000 26.93790 -0.06657523
## 13 x_shape 54.26015 47.83972 16.76996 26.93000 -0.06558334
We can also save these as .png images to make a .gif image (see also
here)
for (ilvs in 1:nlevels){
i <- which(datasaurus_dozen$dataset == datnames[ilvs])
thiscol <- ifelse(datnames[ilvs] == "dino", "darkseagreen", "grey20")
png(filename = paste0("datasaurus/",datnames[ilvs],".png"))
plot(datasaurus_dozen$x[i], datasaurus_dozen$y[i],
xlab = "x", ylab = "y", las = 1,
xlim = c(10, 105), ylim = c(-5, 105), col = thiscol, pch = 16)
dev.off()
}
When doing confirmatory analysis, we might want to know how strong an
effect is. Data viz is very useful for this task. Lets compare two
datasets that have similar p-values, but very different effect sizes
set.seed(42)
x <- rnorm(1000)
set.seed(420)
y <- 5*x + 3 + rnorm(1000, sd = 15)
set.seed(420)
y2 <- 5*x + 3 + rnorm(1000, sd = 1)
mod1 <- lm(y ~ x)
mod2 <- lm(y2 ~ x)
#Compare the pvalues on the slopes
summary(mod1)
##
## Call:
## lm(formula = y ~ x)
##
## Residuals:
## Min 1Q Median 3Q Max
## -43.201 -10.330 0.395 9.634 46.694
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) 2.8054 0.4614 6.080 1.71e-09 ***
## x 4.2096 0.4603 9.145 < 2e-16 ***
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 14.59 on 998 degrees of freedom
## Multiple R-squared: 0.07732, Adjusted R-squared: 0.07639
## F-statistic: 83.63 on 1 and 998 DF, p-value: < 2.2e-16
summary(mod2)
##
## Call:
## lm(formula = y2 ~ x)
##
## Residuals:
## Min 1Q Median 3Q Max
## -2.88004 -0.68868 0.02634 0.64229 3.11291
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) 2.98703 0.03076 97.11 <2e-16 ***
## x 4.94731 0.03069 161.21 <2e-16 ***
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 0.9724 on 998 degrees of freedom
## Multiple R-squared: 0.963, Adjusted R-squared: 0.963
## F-statistic: 2.599e+04 on 1 and 998 DF, p-value: < 2.2e-16
par(mfrow = c(1,2))
plot(x,y, pch = 16, col = grey(0.5,0.5), las = 1)
abline(mod1, lwd = 2, col = 'red')
plot(x,y2, pch = 16, col = grey(0.5,0.5), las = 1)
abline(mod2, lwd = 2, col = 'red')
Plots with less ‘add-ons’ tend to communicate the key message more
clearly. For instance, just like excel plots dont:
x <- rnorm(100)
dat <- data.frame(x = x, y = 0.25*x + rnorm(100, sd = 0.2))
library(ggplot2)
library(ggthemes)
ggplot(dat, aes(x = x, y = y)) + geom_point() +
theme_excel()
You can get additional themes for ggplot2 using this excellent
package.
A cleaner view:
ggplot(dat, aes(x = x, y = y)) + geom_point() +
theme_base()
Or simply:
plot(dat$x, dat$y, xlab = "x", ylab = "y", las = 1)
A good principle is to not use ‘ink’ on figures that isn’t needed to
communicate your message. Tufte
takes the ‘less ink’ philosophy to the extreme:
ggplot(dat, aes(x = x, y = y)) + geom_point() +
theme_tufte()+theme(axis.text=element_text(size=20),
axis.title=element_text(size=20))
In general I think ggplot2 is appropriate for
problems of intermediate complexity. Like this:
Base R is great if you just want to plot a barplot quickly, or do an x-y
plot. ggplot2 comes into its own for slight more complex plots, like
having multiple panels for different groups or colouring lines by a 3rd
factor. But once you move to really complex plots, like overlaying a
subplot on a map, ggplot2 becomes very difficult, if not impossible. At
that point it is better to move back to Base R. ggplot2 can also get
very fiddly if you are very specific about your plots, like having
certain colours, or the labels in a certain way.
As an example, ggplot2 is great for data like this:
x1 <- rnorm(30)
grps <- letters[c(rep(1, 10), rep(2, 10), rep(3, 10))]
y1 <- x1 + c(rep(1, 10), rep(-1, 10), rep(2, 10)) + rnorm(30)
dat <- data.frame(x = x1, grps = grps, y = y1)
head(dat)
## x grps y
## 1 1.15862941 a 5.015377
## 2 0.89667985 a 1.109440
## 3 0.04423754 a 2.122226
## 4 0.27715868 a 1.863923
## 5 0.02435753 a 1.087412
## 6 1.54113178 a 3.839985
ggplot(dat, aes(x = x1, y = y1, color = grps)) +
geom_point() + theme_bw()
It is also pretty handy for faceting:
ggplot(dat, aes(x = x1, y = y1)) +
geom_point() + facet_wrap(~grps)+
theme_bw()
The key with ggplot2 is to have your data in a data-frame.
In reality both ggplot2 and base R graphics are worth learning, but I
would start with learning the basics of base R graphics and then move
onto ggplot2 if you want to quickly plot lots of structured data-sets.
In Mariani et al. they plot rates of seafood fraud by several European
countries. While its a foundational study that establishes improvement
in the accuracy of food labelling, their graphics could be improved in
several ways.
First they use perspective pies. This makes it incredibly hard to
compare the two groups (fish that are labelled/mislabelled). Humans are
very bad at comparing angles and pretty bad at comparing areas. With the
perspective you can’t even compare the areas properly. They do provide
the raw numbers, but then, why bother with the pies?
Note that the % pies misrepresent the data slightly because the %
figures are actually odds ratios (mis-labels / correct labels), rather
than percent (mis-labeels / total samples).
Second the pies are coloured red/green, which will be hard for red-green
colourblind people to see.
Third, they have coloured land blue on their map, so it appears to be
ocean at first look.
Fourth, the map is not really neccessary. There are no spatial patterns
going on that the authors want to draw attention to. I guess having a
map does emphasize that the study is in Europe. Finally, the size of
each pie is scaled to the sample size, but the scale bar for the sample
size shows a sample of only 30, whereas most of their data are for much
larger samples sizes (>200). Do you get the impression from the pies
that the UK has 668 samples, whereas Ireland only has 187? Therefore,
from this graphic we have no idea what sample size was used in each
country.
In fact, all the numbers that are difficult to interpret in the figure
are very nicely presented in Table 1.
Below is a start at improving the presentation. For instance, you could
do a simple bar chart, ordering by rate of mislabelling.
cnames <- c('Ireland' ,'UK','Germany','France','Spain','Portugal')
corrlab <- c(180, 647, 145, 146, 267, 178)
mislab <- c(7, 21, 9, 4, 24, 12)
misrate <- 100*signif(mislab / (corrlab + mislab),2)
corrrate <- 100 - misrate
ord <- order(misrate, decreasing = T)
y <- rbind(corrrate, misrate)
par(mar = c(5,4,4,7))
barplot(y[,ord], names.arg = cnames[ord], col = c('skyblue','tomato'), ylab = 'Labelling rate (%)', las = 2)
legend(x=7.5, y = 90, legend = c("Mislabelled", "Correctly labelled"), pch = 16, col = c('tomato','skyblue'), xpd = NA, cex = 0.7)
You could add another subfigure to this, showing the rate by different
species too.
The barplot doesn’t communicate the sample size, but then that is
probably not the main point. The sample sizes are probably best reported
in the table
If we felt the map was essential, then putting barcharts on it would be
more informative. It is not that easy to add barcharts ontop of an
existing map in R, so I would recommend creating the barcharts
seperately, then adding them on in Illustrator or Powerpoint.
We can make a basic map like this:
library(maps)
library(maptools)
map('world', xlim = c(-20, 20), ylim = c(35, 60), col = 'grey', fill = T)
Then create some nice barcharts. We write a loop so we get one barchart
for each country.
nc <- length(cnames)
par(mfrow = c(2,3), oma = c(1,1,1,3))
for (i in 1:nc){
y <- c(mislab[i], corrlab[i])
barplot(y, names.arg = '', las = 2, col = c('tomato','skyblue'), ylim = c(0, corrlab[i]), main = cnames[i], cex.main = 2.4, yaxt = 'n')
byy <- signif(max(y),2)/3
yat <- c(0, min(y), max(y))
axis(2, at = yat, las = 2, cex.axis = 2, labels = F)
axis(2, at = yat[2:3], las = 2, cex.axis = 2, labels = T)
}
legend(x = 2.8, y = 500, legend = c('Fraud', 'Correct'), pch = 15, col = c('tomato','skyblue'), xpd = NA, cex = 2, bty = 'n')
It can be misleading to present % and proportion data on axes that are
not scaled 0 – 100%. For instance, compare these three graphs:
y <- c(70, 72, 68, 73)
x <- 1:4
xnams <- LETTERS[1:4]
par(mfrow = c(1,3), oma = c(1,1,1,3), mar = c(5,6,2,2))
plot(x,y, pch = 3, cex = 2, las = 1, xaxt = 'n', xlab = '', ylab = 'Percent', cex.axis = 2, cex.lab = 2, tcl = 0.5, xlim = c(0, 5), col = 'red', lwd = 3)
axis(1, at = x, labels = xnams, cex.axis = 2, tcl = 0.5)
barplot(y, names.arg = xnams, las = 1, cex.axis = 2, cex.lab = 2, cex.names = 2, ylab = 'Percent')
barplot(y, names.arg = xnams, las = 1, cex.axis = 2, cex.lab = 2, cex.names = 2, ylab = 'Percent', ylim = c(0, 100))
Alot of thought should go into choosing colour scales for graphs for
instance- will it print ok? will colour blind people be able to see
this? does the scale create artificial visual breaks in the data?
Luckily there is a package to help you make the right decision for a
colour scale, it is called RColorBrewer
. Check out colorbrewer.org for
a helpful interactive web interface for choosing colours.
Here I recreate the map of that in Cinner et al. 2016 Nature for fish
biomass (using dummy data, as I don’t have their data).
First let’s specify some dummy data
fishbio <- c(3.2, 3.3, 3.4, 6, 9, 3.7,3.9,7, 8, 5, 6, 4)
longs <- c(95.59062 ,96.50676,121.05892,128.14529,135.00157,166.68020,156.44645,146.75308, 150.8980, 151.1395, 142.9253, 119.0074)
lats <- c(4.3201110,1.9012211, -7.4197367, 0.4173821 , 7.2730141, -19.8772305, -28.3750059, -16.9918706, -21.985131, -9.422199, -2.899138, 1.932759)
library(RColorBrewer)
library(maps)
#Create the colours for locations
cols <- brewer.pal(9, 'RdYlGn')
colsf <- colorRampPalette(cols)
cols100 <- colsf(100)
breaks <- seq(min(fishbio)-0.01, max(fishbio)+0.01, length.out = 100)
icol <- cut(fishbio, breaks = breaks, labels = F)
fishcols <- cols100[icol]
#Plot locations
map('world', xlim = c(80, 180), ylim = c(-35, 35),interior = F, fill = T, col = 'grey')
points(longs, lats, pch = 16, col = fishcols, cex = 2)
points(longs, lats, pch = 1, cex = 2)
Using red-green palettes makes it hard for colour blind people. Also,
using a diverging palette makes it look like there is something
important about the middle point (yellow). A better palette to use would
be one of the sequential ones. Using reds (and reversing it using
rev()
) emphasises the worst places. We could use greens and emphasise
the best places too. I am using a light grey for the fill so that the
points stand out more.
#Create sequential colours for locations
cols <- rev(brewer.pal(9, 'Reds'))
colsf <- colorRampPalette(cols)
cols100 <- colsf(100)
breaks <- seq(min(fishbio)-0.01, max(fishbio)+0.01, length.out = 100)
icol <- cut(fishbio, breaks = breaks, labels = F)
fishcols <- cols100[icol]
#Plot locations
map('world', xlim = c(80, 180), ylim = c(-35, 35),interior = F, fill = T, col = 'grey90')
points(longs, lats, pch = 16, col = fishcols, cex = 2)
points(longs, lats, pch = 1, cex = 2)
To make it easier to understand, let’s look at these again as contour
plots. I will use a more appropriate diverging palette to the red-green
one though.
z <- matrix(rep(1:10, 10), nrow = 10)
filled.contour(z, col = brewer.pal(9, 'Reds'), nlevels = 10)
filled.contour(z, col = brewer.pal(9, 'RdBu'), nlevels = 10)
Notice the diverging pallette creates an artificial split at yellow
One of the only legitimate uses for pie graphs (I think) is visualising
the colour scales. Here is how:
reds <- brewer.pal(9, 'Reds')
greens <- brewer.pal(9, 'Greens')
blues <- brewer.pal(9, 'Blues')
rdylgn <- brewer.pal(9, 'RdYlGn')
rdbu <- brewer.pal(9, 'RdBu')
dark2 <- brewer.pal(8, 'Dark2')
par(mfrow = c(2,3), mar = c(0,0,0,0), oma = c(0,0,0,0))
pie(rep(1, 9), col = reds)
pie(rep(1, 9), col = greens)
pie(rep(1, 9), col = blues)
pie(rep(1, 9), col = rdylgn)
pie(rep(1, 9), col = rdbu)
pie(rep(1, 9), col = dark2)
People are bad at interpreting rates, we just can’t get our heads around
accumulation very well. Here is a numerical example. Check out the below
figure and ask yourself:
At what time is the number of people in the shopping centre declining?
Would you say it is at point A, B, C or D?
Before you proceed with code below, take the poll:
Here is how we made the figure and generated the data:
par(mar = c(4,4.5,2,2), mgp = c(3,1,0))
plot(times, inrate_err, type = 'l', xlab = 'Hour of day', ylab = 'People per 10 minutes', las = 1, cex.axis = 2, lwd = 3, col = 'darkblue', cex.lab = 2, ylim = c(0, 12))
lines(times, outrate_err, lwd = 3, col = 'tomato')
abline(v = 12, lwd = 2, col = grey(0.5,0.5))
text(12, 13, 'A', xpd = NA, cex = 2)
abline(v = 13.5, lwd = 2, col = grey(0.5,0.5))
text(13.5, 13, 'B', xpd = NA, cex = 2)
abline(v = 14.2, lwd = 2, col = grey(0.5,0.5))
text(14.2, 13, 'C', xpd = NA, cex = 2)
abline(v = 15.8, lwd = 2, col = grey(0.5,0.5))
text(15.8, 13, 'D', xpd = NA, cex = 2)
legend('bottomleft', legend = c('Entering', 'Leaving'), lwd = 2, col = c('darkblue','tomato'), cex = 1.5, xpd = NA)
Let’s plot the total number of people:
par(mar = c(5,5.5,2,2), mgp = c(4,1,0))
plot(times, cumsum(inrate_err) - cumsum(outrate_err), type = 'l', xlab = 'Hour of day', ylab = 'People in shopping centre', las = 1, cex.axis = 2, lwd = 3, col = 'darkblue', cex.lab = 2, ylim = c(0, 120))
abline(v = 12, lwd = 2, col = grey(0.5,0.5))
text(12, 130, 'A', xpd = NA, cex = 2)
abline(v = 13.5, lwd = 2, col = grey(0.5,0.5))
text(13.5, 130, 'B', xpd = NA, cex = 2)
abline(v = 14.1, lwd = 2, col = 'tomato')
text(14.2, 130, 'C', xpd = NA, cex = 2)
abline(v = 15.8, lwd = 2, col = grey(0.5,0.5))
text(15.8, 130, 'D', xpd = NA, cex = 2)
Hopefully the answer is obvious now. So the right scales can help make
interpretation much easier.
The construction of a simple chart in R can be a surprisingly long piece
of code. Here is an example to get you started. Don’t be afraid to
experiment!
# --------------- #
# Make some data
# --------------- #
set.seed(42)
n <- 11
x <- rnorm(n, mean = seq(18, 25, length.out = n))
y <- rnorm(n, mean =seq(26, 18, length.out = n))
z <- rnorm(n, mean = 22)
t <- 2005:(2005+n-1)
datnames <- c('Almonds', 'Peanuts', 'Hazelnuts')
plot(t, x)
lines(t, y)
lines(t, z)
Which look terrible. Let’s build a better chart.
# Package for colours
library(RColorBrewer)
#Set axis limits
ymax <- 30
ylim <- c(15, ymax)
xlim <- c(min(t), max(t))
#Define colours
cols <- brewer.pal(3, 'Dark2')
#Parameters for plotting
lwd <- 2
xlabels <- seq(min(t), max(t), by = 5)
ylabels <- seq(0, ymax, by = 5)
#Set the window params
par(mar = c(5,5,4,4))
#Build the plot
plot(t, x, type = 'l', bty = 'n', xaxt = 'n', yaxt = 'n',
ylim = ylim, xlim = xlim, lwd = lwd, col = cols[1],
xaxs = 'i', yaxs = 'i',
xlab = 'Time (yrs)',
ylab = '',
main = 'Changing price of nuts ($/kg)')
#Add more lines
lines(t, y, lwd = lwd, col = cols[2])
lines(t, z, lwd = lwd, col = cols[3])
#Add labels to lines
text(t[n], x[n], datnames[1], adj = c(0, 0), xpd = NA, col = cols[1])
text(t[n], y[n], datnames[2], xpd = NA, adj = c(0, 0), col = cols[2])
text(t[n], z[n], datnames[3], xpd = NA, adj = c(0, 0), col = cols[3])
# Add custom axes
axis(1, col = 'white', col.ticks = 'black', labels = xlabels, at = xlabels)
axis(1, col = 'white', col.ticks = 'black', labels = NA, at = t)
axis(2, col = 'white', col.ticks = 'black', las =1, labels = ylabels, at = ylabels)
An infographic of chart types: Visual
vocabulary
Adding Features to your Charts
We saw in the previous charts some basic and well-known types of charts that googleVis offers to users. Before continuing with other, more sophisticated charts in the next parts we are going to “dig a little deeper” and see some interesting features of those we already know.
Read the examples below to understand the logic of what we are going to do and then test yous skills with the exercise set we prepared for you. Lets begin!
Answers to the exercises are available here.
Package & Data frame
As you already know, the first thing you have to do is install and load the googleVis package with:
install.packages("googleVis")
library(googleVis)
Secondly we will create an experimental data frame which will be used for our charts’ plotting. You can create it with:
df=data.frame(name=c("James", "Curry", "Harden"),
Pts=c(20,23,34),
Rbs=c(13,7,9))
NOTE: The charts are created locally by your browser. In case they are not displayed at once press F5 to reload the page.
Customizing Chart
We are going to use the two-axis Line Chart we created in part 1. This is the code we used, in case you forgot it:
LineC2 <- gvisLineChart(df, "name", c("Pts","Rbs"),
options=list(
series="[{targetAxisIndex: 0},
{targetAxisIndex:1}]",
vAxes="[{title:'Pts'}, {title:'Rbs'}]"
))
plot(LineC2)
Colours
To set the color of every line we can use:
series="[{color:'green', targetAxisIndex: 0,
Exercise 1
Change the colours of your line chart to green and yellow respectively and plot the chart.
Line Width
You can determine the line width of every line with:
series="[{color:'green',targetAxisIndex: 0, lineWidth: 3},
Exercise 2
Change the line width of your lines to 3 and 6 respectively and plot the chart.
Dashed lines
You can tranform your lines to dashed with:
series="[{color:'green', targetAxisIndex: 0,
lineWidth: 1, lineDashStyle: [2, 2, 20, 2, 20, 2]},
There are many styles and colours available and you can find them here.
Exercise 3
Choose two different styles of dashed lines for every line of your chart from the link above and plot your chart.
Point Shape
With the pointShape
option you can choose from a variety of shapes for your points.
We will use the scatter chart we built in part 3 to see how it works. Here is the code:
ScatterCD <- gvisScatterChart(cars,
options=list(
legend="none",
pointSize=3,lineWidth=2,
title="Cars", vAxis="{title:'speed'}",
hAxis="{title:'dist'}",
width=600, height=300))
plot(ScatterCD)
Exercise 4
Change the shape of your scatter chart’s points to ‘square’ and plot it. HINT: Use pointShape
.
Exercise 5
Change the shape of your scatter chart’s points to ‘triangle’, their point size to 7 and plot it.
Edit Button
A really useful and easy feature that googleVis provides is the edit button which gives the user the ability to customize the chart in an automated way.
options=list(gvis.editor="Edit!"))
Exercise 6
Add an edit button in the scatter chart you just created. HINT: Use gvis.editor
.
Chart with more options
Now let’s see how we can create a chart with many features that can enhance its appearance. We will use again the 2-axis line that we used before.
LineCD2 <- gvisLineChart(df, "name", c("Pts","Rbs"),
options=list(
series="[{color:'green',targetAxisIndex: 0, lineWidth: 3,
lineDashStyle: [14, 2, 2, 7]},
{color:'yellow',targetAxisIndex:1,lineWidth: 6,
lineDashStyle: [10, 2]}]",
vAxes="[{title:'Pts'}, {title:'Rbs'}]"
))
plot(LineCD2)
Background color
You can decide the background color of your chart with:
backgroundColor="red",
Exercise 7
Set the background color of your line chart to “lightblue” and plot it. HINT: Use backgroundColor
.
Title
To give a title and decide its features you can use:
title="Title",
titleTextStyle="{color:'orange',
fontName:'Courier',
fontSize:14}",
Exercise 8
Give a title of your choise to the line chart and set its font to blue, Courier of size 16. HINT: Use titleTextStyle
.
Curve Type & Legend
Another nice-looking choise that googleVis gives you is to display the lines like curves with:
curveType="function"
You can also move the legend of your chart to the bottom with:
legend="bottom"
Exercise 9
Smooth the lines of your line chart by setting the curveType
option to function and move the legend
to the bottom. HINT: Use curveType
and legend
.
Axes features
Finally you can “play” with your axes. This is an example:
vAxis="{gridlines:{color:'green', count:4}}",
hAxis="{title:'City', titleTextStyle:{color:'red'}}",
series="[{color:'yellow', targetAxisIndex: 0},
{color: 'brown',targetAxisIndex:1}]",
vAxes="[{title:'val1'}, {title:'val2'}]",
Exercise 10
Give the title “Name” to your hAxis and color it orange. Separate your vAxis with 3 red gridlines. HINT: Use titleTextStyle
and gridlines
The post R Weekly Bulletin Vol – XII appeared first on .
]]>This week’s R bulletin will cover topics on how to resolve some common errors in R.
We will also cover functions like do.call, rename, and lapply. Click To TweetHope you like this R weekly bulletin. Enjoy reading!
1. Find and Replace – Ctrl+F
2. Find Next – F3
3. Find Previous – Shift+F3
There can be two reasons for this error to show up when we run an R script: 1) A file/connection can’t be opened because R can’t find it (mostly due to an error in the path) 2) Failure in .onLoad() because a package can’t find a system dependency
Example:
symbol = "AXISBANK" noDays = 1 dirPath = paste(getwd(), "/", noDays, " Year Historical Data", sep = "") fileName = paste(dirPath, symbol, ".csv", sep = "") data = as.data.frame(read.csv(fileName))
Warning in file(file, “rt”): cannot open file ‘C:/Users/Madhukar/Documents/
1 Year Historical DataAXISBANK.csv’: No such file or directory
Error in file(file, “rt”): cannot open the connection
We are getting this error because we have specified the wrong path to the “dirPath” object in the code. The right path is shown below. We missed adding a forward slash after “Year Historical Data” in the paste function. This led to the wrong path, and hence the error.
dirPath = paste(getwd(),”/”,noDays,” Year Historical Data/”,sep=””)
After adding the forward slash, we re-ran the code. Below we can see the right dirPath and fileName printed in the R console.
Example:
symbol = "AXISBANK" noDays = 1 dirPath = paste(getwd(), "/", noDays, " Year Historical Data/", sep = "") fileName = paste(dirPath, symbol, ".csv", sep = "") data = as.data.frame(read.csv(fileName)) print(head(data, 3))
This error arises when an R package is not loaded properly or due to the misspelling of the function names.
When we run the code shown below, we get a “could not find the function ymd” error in the console. This is because we have misspelled the “ymd” function as “ymed”. If we do not load the required packages, this will also throw up a “could not find function ymd” error.
Example:
# Read NIFTY price data from the csv file df = read.csv("NIFTY.csv") # Format date dates = ymed(df$DATE)
Error in eval(expr, envir, enclos): could not find function “ymed”
This error occurs when one tries to assign a vector of values to an existing object and the lengths do not match up.
In the example below, the stock price data of Axis bank has 245 rows. In the code, we created a sequence “s” of numbers from 1 to 150. When we try to add this sequence to the Axis Bank data set, it throws up a “replacement error” as the lengths of the two do not match. Thus to resolve such errors one should ensure that the lengths match.
Example:
symbol = "AXISBANK" ; noDays = 1 ; dirPath = paste(getwd(),"/",noDays," Year Historical Data/",sep="") fileName = paste(dirPath,symbol,".csv",sep="") df = as.data.frame(read.csv(fileName)) # Number of rows in the dataframe "df" n = nrow(df); print(n); # create a sequence of numbers from 1 to 150 s = seq(1,150,1) # Add a new column "X" to the existing data frame "df" df$X = s print(head(df,3))
Error in $<-.data.frame(*tmp*, “X”, value = c(1, 2, 3, 4, 5, 6, 7, : replacement has 150 rows, data has 245
The do.call function is used for calling other functions. The function which is to be called is provided as the first argument to the do.call function, while the second argument of the do.call function is a list of arguments of the function to be called. The syntax for the function is given as:
do.call (function_name, arguments)
Example: Let us first define a simple function that we will call later in the do.call function.
numbers = function(x, y) { sqrt(x^3 + y^3) } # Now let us call this 'numbers' function using the do.call function. We provide the function name as # the first argument to the do.call function, and a list of the arguments as the second argument. do.call(numbers, list(x = 3, y = 2))
[1] 5.91608
The rename function is part of the dplyr package, and is used to rename the columns of a data frame. The syntax for the rename function is to have the new name on the left-hand side of the = sign, and the old name on the right-hand side. Consider the data frame “df” given in the example below.
Example:
library(dplyr) Tic = c("IOC", "BPCL", "HINDPETRO", "ABAN") OP = c(555, 570, 1242, 210) CP = c(558, 579, 1248, 213) df = data.frame(Tic, OP, CP) print(df)
# Renaming the columns as 'Ticker', 'OpenPrice', and 'ClosePrice'. This can be done in the following # manner: renamed_df = rename(df, Ticker = Tic, OpenPrice = OP, ClosePrice = CP) print(renamed_df)
The lapply function is part of the R base package, and it takes a list “x” as an input, and returns a list of the same length as “x”, each element of which is the result of applying a function to the corresponding element of X. The syntax of the function is given as:
lapply(x, Fun)
where,
x is a vector (atomic or list)
Fun is the function to be applied
Example 1:
Let us create a list with 2 elements, OpenPrice and the ClosePrice. We will compute the mean of the values in each element using the lapply function.
x = list(OpenPrice = c(520, 521.35, 521.45), ClosePrice = c(521, 521.1, 522)) lapply(x, mean)
$OpenPrice
[1] 520.9333
$ClosePrice
[1] 521.3667
Example 2:
x = list(a = 1:10, b = 11:15, c = 1:50) lapply(x, FUN = length)
$a
[1] 10
$b
[1] 5
$c
[1] 50
We hope you liked this bulletin. In the next weekly bulletin, we will list more interesting ways and methods plus R functions for our readers.
The post R Weekly Bulletin Vol – XII appeared first on .
In the development of operational loss models, it is important to identify which distribution should be used to model operational risk measures, e.g. frequency and severity. For instance, why should we use the Gamma distribution instead of the Inverse Gaussian distribution to model the severity?
In my previous post https://statcompute.wordpress.com/2016/11/20/modified-park-test-in-sas, it is shown how to use the Modified Park test to identify the mean-variance relationship and then decide the corresponding distribution of operational risk measures. Following the similar logic, we can also leverage the flexibility of the Tweedie distribution to accomplish the same goal. Based upon the parameterization of a Tweedie distribution, the variance = Phi * (Mu ** P), where Mu is the mean and P is the power parameter. Depending on the specific value of P, the Tweedie distribution can accommodate several important distributions commonly used in the operational risk modeling, including Poisson, Gamma, Inverse Gaussian. For instance,
In the example below, it is shown that the value of P is in the neighborhood of 1 for the frequency measure and is near 3 for the severity measure and that, given P closer to 3, the Inverse Gaussian regression would fit the severity better than the Gamma regression.
library(statmod) library(tweedie) profile1 <- tweedie.profile(Claim_Count ~ Age + Vehicle_Use, data = AutoCollision, p.vec = seq(1.1, 3.0, 0.1), fit.glm = TRUE) print(profile1$p.max) # [1] 1.216327 # The P parameter close to 1 indicates that the claim_count might follow a Poisson-like distribution profile2 <- tweedie.profile(Severity ~ Age + Vehicle_Use, data = AutoCollision, p.vec = seq(1.1, 3.0, 0.1), fit.glm = TRUE) print(profile2$p.max) # [1] 2.844898 # The P parameter close to 3 indicates that the severity might follow an Inverse Gaussian distribution BIC(glm(Severity ~ Age + Vehicle_Use, data = AutoCollision, family = Gamma(link = log))) # [1] 360.8064 BIC(glm(Severity ~ Age + Vehicle_Use, data = AutoCollision, family = inverse.gaussian(link = log))) # [1] 350.2504
Together with the Modified Park test, the estimation of P in a Tweedie distribution is able to help us identify the correct distribution employed in operational loss models in the context of GLM.