We’ve been loading the Gapminder data as a data.frame from the
gapminder data package. We haven’t been explicitly writing any data or derived results to file. In real life, you’ll bring rectangular data into and out of R all the time. Sometimes you’ll need to do same for non-rectangular objects.
How do you do this? What issues should you think about?
Data import generally feels one of two ways:
In the second case, and as the first cases progresses, you actually know a lot about how the data is / should be. My main import advice: use the arguments of your import function to get as far as you can, as fast as possible. Novice code often has a great deal of unnecessary post import fussing around. Read the docs for the import functions and take maximum advantage of the arguments to control the import.
There will be many occasions when you need to write data from R. Two main examples:
First tip: today’s outputs are tomorrow’s inputs. Think back on all the pain you have suffered importing data and don’t inflict such pain on yourself!
Second tip: don’t be too cute or clever. A plain text file that is readable by a human being in a text editor should be your default until you have actual proof that this will not work. Reading and writing to exotic or proprietary formats will be the first thing to break in the future or on a different computer. It also creates barriers for anyone who has a different toolkit than you do. Be software-agnostic. Aim for future-proof and moron-proof.
How does this fit with our emphasis on dynamic reporting via R Markdown? There is a time and place for everything. There are projects and documents where the scope and personnel will allow you to geek out with
knitr and R Markdown. But there are lots of good reasons why (parts of) an analysis should not (only) be embedded in a dynamic report. Maybe you are just doing data cleaning to produce a valid input dataset. Maybe you are making a small but crucial contribution to a giant multi-author paper. Etc. Also remember there are other tools and workflows for making something reproducible. I’m looking at you, make.
The main function we will be using is readr, which provides drop-in substitutes for
read.table() and friends. However, to make some points about data export and import, it is nice to reorder factor levels. For that, we will also load and use the forcats package.
library(tidyverse) ## Loading tidyverse: ggplot2 ## Loading tidyverse: tibble ## Loading tidyverse: tidyr ## Loading tidyverse: readr ## Loading tidyverse: purrr ## Loading tidyverse: dplyr ## Conflicts with tidy packages ---------------------------------------------- ## filter(): dplyr, stats ## lag(): dplyr, stats library(forcats)
We could load the data from the package as usual, but instead we will load it from tab delimited file. The gapminder package includes the data normally found in the
gapminder data frame as a
.tsv. So let’s get the path to that file on your system.
(gap_tsv <- system.file("gapminder.tsv", package = "gapminder")) ##  "/Users/jenny/resources/R/library/gapminder/gapminder.tsv"
The workhorse data import function of readr is
read_delim(). Here we’ll use a variant,
read_tsv(), that anticipates tab-delimited data:
gapminder <- read_tsv(gap_tsv) ## Parsed with column specification: ## cols( ## country = col_character(), ## continent = col_character(), ## year = col_integer(), ## lifeExp = col_double(), ## pop = col_integer(), ## gdpPercap = col_double() ## ) str(gapminder, give.attr = FALSE) ## Classes 'tbl_df', 'tbl' and 'data.frame': 1704 obs. of 6 variables: ## $ country : chr "Afghanistan" "Afghanistan" "Afghanistan" "Afghanistan" ... ## $ continent: chr "Asia" "Asia" "Asia" "Asia" ... ## $ year : int 1952 1957 1962 1967 1972 1977 1982 1987 1992 1997 ... ## $ lifeExp : num 28.8 30.3 32 34 36.1 ... ## $ pop : int 8425333 9240934 10267083 11537966 13079460 14880372 12881816 13867957 16317921 22227415 ... ## $ gdpPercap: num 779 821 853 836 740 ...
For full flexibility re: specifying the delimiter, you can always use
There’s a similar convenience wrapper for comma-separated values,
The most noticeable difference between the readr functions and base is that readr does NOT convert strings to factors by default. In the grand scheme of things, this is better default behavior, although we go ahead and convert them to factor here. Do not be deceived – in general, you will do less post-import fussing if you use readr.
gapminder <- gapminder %>% mutate(country = factor(country), continent = factor(continent)) str(gapminder) ## Classes 'tbl_df', 'tbl' and 'data.frame': 1704 obs. of 6 variables: ## $ country : Factor w/ 142 levels "Afghanistan",..: 1 1 1 1 1 1 1 1 1 1 ... ## $ continent: Factor w/ 5 levels "Africa","Americas",..: 3 3 3 3 3 3 3 3 3 3 ... ## $ year : int 1952 1957 1962 1967 1972 1977 1982 1987 1992 1997 ... ## $ lifeExp : num 28.8 30.3 32 34 36.1 ... ## $ pop : int 8425333 9240934 10267083 11537966 13079460 14880372 12881816 13867957 16317921 22227415 ... ## $ gdpPercap: num 779 821 853 836 740 ...
readr::read_delim() and friends. Use the arguments!
The Gapminder data is too clean and simple to show off the great features of readr, so I encourage you to check out the vignette on column types. There are many variable types that you will be able to parse correctly upon import, thereby eliminating a great deal of post-timport fussing.
We need compute something worth writing to file. Let’s create a country-level summary of maximum life expectancy.
gap_life_exp <- gapminder %>% group_by(country, continent) %>% summarise(life_exp = max(lifeExp)) %>% ungroup() gap_life_exp ## # A tibble: 142 × 3 ## country continent life_exp ## <fctr> <fctr> <dbl> ## 1 Afghanistan Asia 43.828 ## 2 Albania Europe 76.423 ## 3 Algeria Africa 72.301 ## 4 Angola Africa 42.731 ## 5 Argentina Americas 75.320 ## 6 Australia Oceania 81.235 ## 7 Austria Europe 79.829 ## 8 Bahrain Asia 75.635 ## 9 Bangladesh Asia 64.062 ## 10 Belgium Europe 79.441 ## # ... with 132 more rows
gap_life_exp data frame is an example of an intermediate result that we want to store for the future and for downstream analyses or visualizations.
The workhorse export function for rectangular data in readr is
write_delim() and friends. Let’s use
write_csv() to get a comma-delimited file.
Let’s look at the first few lines of
gap_life_exp.csv. If you’re following along, you should be able to open this file or, in a shell, use
head on it.
country,continent,life_exp Afghanistan,Asia,43.828 Albania,Europe,76.423 Algeria,Africa,72.301 Angola,Africa,42.731 Argentina,Americas,75.32
This is pretty decent looking, though there is no visible alignment or separation into columns. Had we used the base function
read.csv(), we would be seeing rownames and lots of quotes, unless we had explicitly shut that down. Nicer default behavior is the main reason we are using
View()in RStudio or open it in Microsoft Excel (!) but don’t succumb to the temptation to start doing artisanal data manipulations there … get back to R and construct commands that you can re-run the next 15 times you import/clean/aggregate/export the same dataset. Trust me, it will happen.
It turns out these self-imposed rules are often in conflict with one another
iis an input for script
i + 1
Example: after performing the country-level summarization, we reorder the levels of the country factor, based on life expectancy. This reordering operation is conceptually important and must be embodied in R commands stored in a script. However, as soon as we write
gap_life_exp to a plain text file, that meta-information about the countries is lost. Upon re-import with
read_delim() and friends, we are back to alphabetically ordered factor levels. Any measure we take to avoid this loss immediately breaks another one of our rules.
So what do I do? I must admit I save (and re-load) R-specific binary files. Right after I save the plain text file. Belt and suspenders.
I have toyed with the idea of writing import helper functions for a specific project, that would re-order factor levels in principled ways. They could be defined in one file and called from many. This would also have a very natural implementation within a workflow where each analytical project is an R package. But so far it has seemed too much like yak shaving. I’m intrigued by a recent discussion of putting such information in YAML frontmatter (see Martin Fenner blog post Using YAML frontmatter with CSV).
The topic of factor level reordering is covered elsewhere, so let’s Just. Do. It. I reorder the country factor levels according to the life expectancy summary we’ve already computed.
head(levels(gap_life_exp$country)) # alphabetical order ##  "Afghanistan" "Albania" "Algeria" "Angola" "Argentina" ##  "Australia" gap_life_exp <- gap_life_exp %>% mutate(country = fct_reorder(country, life_exp)) head(levels(gap_life_exp$country)) # in increasing order of maximum life expectancy ##  "Sierra Leone" "Angola" "Afghanistan" "Liberia" ##  "Rwanda" "Mozambique" head(gap_life_exp) ## # A tibble: 6 × 3 ## country continent life_exp ## <fctr> <fctr> <dbl> ## 1 Afghanistan Asia 43.828 ## 2 Albania Europe 76.423 ## 3 Algeria Africa 72.301 ## 4 Angola Africa 42.731 ## 5 Argentina Americas 75.320 ## 6 Australia Oceania 81.235
Note that the row order of
gap_life_exp has not changed. I could choose to reorder the rows of the data frame if, for example, I was about to prepare a table to present to people. But I’m not, so I won’t.
If you have a data frame AND you have exerted yourself to rationalize the factor levels, you have my blessing to save it to file in a way that will preserve this hard work upon re-import. Use
saveRDS() serializes an R object to a binary file. It’s not a file you will able to open in an editor, diff nicely with Git(Hub), or share with non-R friends. It’s a special purpose, limited use function that I use in specific situations.
The opposite of
readRDS(). You must assign the return value to an object. I highly recommend you assign back to the same name as before. Why confuse yourself?!?
rm(gap_life_exp) gap_life_exp ## Error in eval(expr, envir, enclos): object 'gap_life_exp' not found gap_life_exp <- readRDS("gap_life_exp.rds") gap_life_exp ## # A tibble: 142 × 3 ## country continent life_exp ## <fctr> <fctr> <dbl> ## 1 Afghanistan Asia 43.828 ## 2 Albania Europe 76.423 ## 3 Algeria Africa 72.301 ## 4 Angola Africa 42.731 ## 5 Argentina Americas 75.320 ## 6 Australia Oceania 81.235 ## 7 Austria Europe 79.829 ## 8 Bahrain Asia 75.635 ## 9 Bangladesh Asia 64.062 ## 10 Belgium Europe 79.441 ## # ... with 132 more rows
saveRDS() has more arguments, in particular
compress for controlling compression, so read the help for more advanced usage. It is also very handy for saving non-rectangular objects, like a fitted regression model, that took a nontrivial amount of time to compute.
You will eventually hear about
load() and even
save.image(). You may even see them in documentation and tutorials, but don’t be tempted. Just say no. These functions encourage unsafe practices, like storing multiple objects together and even entire workspaces. There are legitimate uses of these functions, but not in your typical data analysis.
Concrete demonstration of how non-alphabetical factor level order is lost with
read_delim() workflows but maintained with
(country_levels <- tibble(original = head(levels(gap_life_exp$country)))) ## # A tibble: 6 × 1 ## original ## <chr> ## 1 Sierra Leone ## 2 Angola ## 3 Afghanistan ## 4 Liberia ## 5 Rwanda ## 6 Mozambique write.table(gfits, "gfits.tsv", sep = "\t") ## Error in is.data.frame(x): object 'gfits' not found saveRDS(gap_life_exp, "gap_life_exp.rds") rm(gap_life_exp) head(gap_life_exp) # will cause error! proving gfits is really gone ## Error in head(gap_life_exp): object 'gap_life_exp' not found gap_via_csv <- read_csv("gap_life_exp.csv") %>% mutate(country = factor(country)) ## Parsed with column specification: ## cols( ## country = col_character(), ## continent = col_character(), ## life_exp = col_double() ## ) gap_via_rds <- readRDS("gap_life_exp.rds") country_levels <- country_levels %>% mutate(via_csv = head(levels(gap_via_csv$country)), via_rds = head(levels(gap_via_rds$country))) country_levels ## # A tibble: 6 × 3 ## original via_csv via_rds ## <chr> <chr> <chr> ## 1 Sierra Leone Afghanistan Sierra Leone ## 2 Angola Albania Angola ## 3 Afghanistan Algeria Afghanistan ## 4 Liberia Angola Liberia ## 5 Rwanda Argentina Rwanda ## 6 Mozambique Australia Mozambique
Note how the original, post-reordering country factor levels are restored using the
readRDS() strategy but revert to alphabetical ordering using
One last method of saving and restoring data deserves a mention:
dput() offers this odd combination of features: it creates a plain text representation of an R object which still manages to be quite opaque. If you use the
file = argument,
dput() can write this representation to file but you won’t be tempted to actually read that thing.
dput() creates an R-specific-but-not-binary representation. Let’s try it out.
## first restore gfits with our desired country factor level order gap_life_exp <- readRDS("gap_life_exp.rds") dput(gap_life_exp, "gap_life_exp-dput.txt")
Now let’s look at the first few lines of the file
structure(list(country = structure(c(3L, 107L, 74L, 2L, 98L, 138L, 128L, 102L, 49L, 125L, 26L, 56L, 96L, 47L, 75L, 85L, 18L, 12L, 37L, 24L, 133L, 13L, 16L, 117L, 84L, 82L, 53L, 9L, 28L, 120L, 22L, 104L, 114L, 109L, 115L, 23L, 73L, 97L, 66L, 71L, 15L, 29L, 20L, 122L, 134L, 40L, 35L, 123L, 38L, 126L, 60L, 25L, 7L, 39L, 59L, 141L, 86L, 140L, 51L, 63L, 64L, 52L, 121L, 135L, 132L,
Huh? Don’t worry about it. Remember we are “writing data for computers”. The partner function
dget() reads this representation back in.
gap_life_exp_dget <- dget("gap_life_exp-dput.txt") country_levels <- country_levels %>% mutate(via_dput = head(levels(gap_life_exp_dget$country))) country_levels ## # A tibble: 6 × 4 ## original via_csv via_rds via_dput ## <chr> <chr> <chr> <chr> ## 1 Sierra Leone Afghanistan Sierra Leone Sierra Leone ## 2 Angola Albania Angola Angola ## 3 Afghanistan Algeria Afghanistan Afghanistan ## 4 Liberia Angola Liberia Liberia ## 5 Rwanda Argentina Rwanda Rwanda ## 6 Mozambique Australia Mozambique Mozambique
Note how the original, post-reordering country factor levels are restored using the
But why on earth would you ever do this?
The main application of this is the creation of highly portable, self-contained minimal examples. For example, if you want to pose a question on a forum or directly to an expert, it might be required or just plain courteous to NOT attach any data files. You will need a monolithic, plain text blob that defines any necessary objects and has the necessary code.
dput() can be helpful for producing the piece of code that defines the object. If you
dput() without specifying a file, you can copy the return value from Console and paste into a script. Or you can write to file and copy from there or add R commands below.
My special dispensation to abandon human-readable, plain text files is even broader than I’ve let on. Above, I give my blessing to store data.frames via
saveRDS(), when you’ve done some rational factor level re-ordering. The same advice and mechanics apply a bit more broadly: you’re also allowed to use R-specific file formats to save vital non-rectangular objects, such as a fitted nonlinear mixed effects model or a classification and regression tree.
We’ve written several files in this tutorial. Some of them are not of lasting value or have confusing filenames. I choose to delete them, while demonstrating some of the many functions R offers for interacting with the filesystem. It’s up to you whether you want to submit this command or not.
file.remove(list.files(pattern = "^gap_life_exp")) ##  TRUE TRUE TRUE
If a delimited file contains fields where a human being has typed, be crazy paranoid because people do really nutty things. Especially people who aren’t in the business of programming and have never had to compute on text. Claim: a person’s regular expression skill is inversely proportional to the skill required to handle the files they create. Implication: if someone has never heard of regular expressions, prepare for lots of pain working with their files.
When the header fields (often, but not always, the variable names) or actual data contain the delimiter, it can lead to parsing and import failures. Two popular delimiters are the comma
, and the TAB
\t and humans tend to use these when typing. If you can design this problem away during data capture, such as by using a drop down menu on an input form, by all means do so. Sometimes this is impossible or undesirable and you must deal with fairly free form text. That’s a good time to allow/force text to be protected with quotes, because it will make parsing the delimited file go more smoothly.
Sometimes, instead of rigid tab-delimiting, whitespace is used as the delimiter. That is, in fact, the default for both
write.table(). Assuming you will write/read variable names from the first line (a.k.a. the
read.table()), they must be valid R variable names … or they will be coerced into something valid. So, for these two reasons, it is good practice to use “one word” variable names whenever possible. If you need to evoke multiple words, use
camelCase to cope. Example: the header entry for the field holding the subject’s last name should be
last name. With the
readr package, “column names are left as is, not munged into valid R identifiers (i.e. there is no
check.names = TRUE)”. So you can get away with whitespace in variable names and yet I recommend that you do not.
Nine simple ways to make it easier to (re)use your data by Ethan P White, Elita Baldridge, Zachary T. Brym, Kenneth J. Locey, Daniel J. McGlinn, Sarah R. Supp.
Tidy data by Hadley Wickham.