-
Notifications
You must be signed in to change notification settings - Fork 3
/
ch-101-exporting_files.rmd
428 lines (256 loc) · 9.61 KB
/
ch-101-exporting_files.rmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
---
output:
html_document:
theme: readable
highlight: tango
self_contained: false
css: textbook.css
---
```{r, echo=F, fig.align="center",out.width="100%"}
knitr::include_graphics("https://media.giphy.com/media/13UPtnr8JdidYA/giphy.gif")
```
# Writing Data
<br>
<br>
<div class="tip">
## Key Concepts
In this chapter, we'll explore the following key concepts:
* CSV, TSV, & Delimited Files
* R Data Sets (RDS)
* RData Format
## Key Takeaways
Too long; didn't read? Here's everything you need to know:
* Importing data is **reading data**; exporting data is **writing data**
* Keep your working directories in mind, all files write to them by default
* Base R function `write.table()` writes most common file types
* Base R function `write.csv()` writes CSVs, TSVs, and more
* Package "readr" has `write*()` functions for each file type
* Save an object with `save()` and `.rds` extensions
* Save objects and workspaces using extension `.RData`
* Write data to your clipboard with `writeClipboard()`
<br>
<br>
<br>
</div>
<br>
<br>
<div class="caution">
<br>
**ATTENTION**
Readers are expected to have read the chapter "Getting Data into R".
<br>
</div>
<br>
<br>
## Functions for Writing Data
We **read data** into R, or *import*, with `read*()` functions.
Similarly, we **write data** from R, or *export*, with `write*()` functions.
* Most base R reading functions have equivalent writing functions
* Most package "readr" functions also have similar writing functions
* Packages for Excel, JSON, and other file formats have writing functions
<br>
What is **writing data**?
Simply put, it's the act of storing data in a location and format of your choosing.
Typically, your data are stored in an object like a matrix or data frame.
It's simply a matter of exporting a data-laden object.
<br>
<br>
### A Brief Note on Working Directories
Unless otherwise specified, data are written to your working directory by default.
* You can often specify different paths to save your data with argument **file =**
* Print your working directory with function `getwd()`
* Change your working directory with function `setwd()`
* Create new directories with function `dir.create()`
* See contents of directories with function `dir()`
<br>
<br>
### Base R's Workhorse Writing Function: `write.table()`
R's workhorse reading function, on which other functions depend, is `read.table()`.
R's workhorse writing function is `write.table()`.
<br>
Function wrappers like `write.csv()` are powered by `write.table()` under the hood.
```{r}
write.csv
```
<br>
If all else fails (and it probably won't), you can depend on `write.table()`.
<br>
<br>
### Writing Text Files: `write.csv()` & `write_csv()`
Comma-separated values (CSV) files are the most common type of output in R.
However, we can use the same `write*()` functions to create TSVs and more.
<br>
**Practice Data:** Let's create a simple data frame to practice writing data.
```{r warning=F, message=F}
name <- c("Fatimah", "Li", "Arnold", "Fede", "Sly") # Character vector
weight <- c(61.4, 68.4, 81.8, 79.9, 90.3) # Double vector
age <- c(29L, 31L, 44L, 33L, 27L) # Integer vector
clients <- data.frame(name, weight, age, # Create data frame
stringsAsFactors = FALSE) # Don't forget this!
clients
```
<br>
**Base R:** Write CSV files using function `write.csv()`.
```{r warning=F, message=F}
write.csv(x = clients, # Write object "clients"
file = "clients.csv") # Write file name and extension
```
**Include Extensions:** When writing a file, *include the extension in the file name*.
* Saving an R script? Include `.r`
* Saving an Excel sheet? Include `.xlsx`
* Saving a CSV? Include `.csv`
<br>
**TSVs & Other Delimiters:** You're not restricted to using commas with `write.csv()`.
```{r warning=F, message=F}
write.csv(x = clients,
file = "clients.tsv", # Use appropriate extension
sep = "\t") # Save as tab-delimited
```
<br>
**Notable Arguments:** Function `write.csv()` has some notable parameters, e.g.
* **x =** specifies the name of the object to write
* **file =** specifies the output file name; requires quotes and extension
* **sep =** specifies the delimiter, e.g. commas, tabs, semicolons, etc.
* **na =** specifies the character(s) to use instead of missing values
<br>
**Package "readr":** Function `write_csv()` is the same as `write.csv()` except:
* Significantly faster at writing data
* Does not write row names automatically
* Cannot write files with non-comma delimiters
* More consistent argument names; **file =** is now **path =**
<br>
**Writing with "readr":** Observe `write_csv()` in action:
```{r warning=F, message=F}
library(readr)
write_csv(x = clients,
path = "clients.csv")
```
<br>
**TSV Files with "readr":** Bummer! Can't write TSV files with `write_csv()`.
Hark! Package "readr" has function `write_tsv()` for precisely that!
```{r warning=F, message=F}
library(readr)
write_tsv(x = clients,
path = "clients.tsv") # Right tool for the job
```
<br>
In fact, package "readr" has writing functions optimized for many file types.
We encourage you to check out each one, e.g. `help(write_delim)`:
* `write_csv()`
* `write_csv2()`
* `write_delim()`
* `write_excel_csv()`
* `write_file()`
* `write_rds()`
* `write_tsv()`
<br>
<br>
```{r, echo=F, fig.cap="Mind blown.", fig.align="center",out.width="75%"}
knitr::include_graphics("https://media3.giphy.com/media/26ufdipQqU2lhNA4g/giphy.gif?cid=790b7611fef46f20fd40e0b7ca12682dfe7b765c777f55e5&rid=giphy.gif")
```
<br>
<br>
## Saving Your Work: R Datasets (RDS)
Manually restoring your workspace to your former session's glory is a pain.
Hence, base R has functions `save()` and `load()` to save objects locally.
<br>
**Saving an Object:** Save your original object, `clients`, as a `.rds` file:
```{r message=F, warning=F}
save(clients,
file = "clients_object.rds")
```
<br>
**Saving More than One Object:** List each object first and save as `.RData`:
```{r message=F, warning=F}
save(age, name, weight, clients,
file = "clients_all.RData")
```
<br>
**Saving your Workspace:** Save your history and all objects with `save.image()`:
```{r message=F, warning=F}
save.image(file = "my_workspace.RData")
```
<br>
**Load Objects & Workspaces:** Simply input the file name into function `load()`:
```{r message=F, warning=F}
load("clients_object.rds") # Load a single object file
load("clients_all.RData") # Load multiple objects
load("my_workspace.RData") # Laod entire workspace
```
<br>
**Why save objects and workspaces?**
* Perfectly reproduce your environment for collaborators
* Load typical header information for scripts, like authors and versions
* Save and load objects that take a lot of time or computing power to create
* We haven't learned many object types, but some are useful when reproduced often
<br>
<br>
## Writing Data to Statistical Software Files
The "foreign" and "haven" packages help read and write files used in SAS, SPSS, etc.
<br>
Package "foreign" uses `write.foreign()` as a catch-all writing function.
Argument **package =** accepts "SPSS", "SAS", and other software names.
It also has wrapper functions like `write_dta()` for Sata files, e.g.
```{r, warning=F, message=F, eval=F}
library(foreign)
write.foreign(df = clients,
datafile = "clients.sas",
package = "SAS")
```
<br>
Package "haven" only has four specific functions rather than a single workhorse:
```{r, warning=F, message=F, eval=F}
library(haven)
write_dta(clients, "clients.dta") # Stata
write_sas(clients, "clients.sas") # SAS
write_sav(clients, "clients.sav") # SPSS
write_xpt(clients, "clients.xpt") # SAS, too
```
<br>
<br>
## Copying Data to Your Clipboard
Read data from the clipboard with `readClipboard()`; write with `writeClipboard()`.
<br>
The concept, briefly:
1. When copying text, it goes to your clipboard - the same as `writeClipboard()`
2. When pasting text, it comes from your clipboard - the same as `readClipboard()`
<br>
```{r, echo=F, fig.cap="You can write character data to your clipboard from R.", fig.align="center", out.width="75%"}
knitr::include_graphics("https://media0.giphy.com/media/56ikf9jD4ZK6s/giphy.gif")
```
<br>
**Character Data Only:** Here, we'll copy two objects to the clipboard.
* Note that only the character data will copy to your clipboard
* Non-characyet data must be coerced with function `as.character()`
```{r warning=F, message=F, eval=F}
txt <- "This is a sentences comprised of text."
num <- 2.718
writeClipboard(txt) # Accepts character data
writeClipboard(num) # Will not accept numeric data
writeClipboard(as.character(num)) # Accepts when coerced to character
```
<br>
<br>
## Copying Data to Excel
There's a "quick and dirty" method to copying and pasting data from R into Excel.
1. Open the tabular data object with function `View()`
2. Highlight each cell, starting at lower-right, ending at upper-left
3. Right click or **Ctrl + C** to copy the RStudio Viewer data
4. Right click or **Ctrl + V** to paste into Excel
<br>
```{r, echo=F, fig.cap="Copy and paste right from your RStudio viewer.", fig.align="center", out.width="75%"}
knitr::include_graphics("figures/copy_viewer.jpg")
```
<br>
<br>
## Further Resources
* [Exporting Data (Quick-R)](https://www.statmethods.net/input/exportingdata.html)
* [R Data Import/Export (CRAN)](https://cran.r-project.org/doc/manuals/r-release/R-data.html)
<br>
<br>
## Works Cited
* SpongBob SquarePants
* Tim & Eric's Awesome Show
* Gravity Falls
<br>
<br>