-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy path571_exporting.Rmd
101 lines (51 loc) · 2.25 KB
/
571_exporting.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
<!--
This file by Martin Monkman
is licensed under a Creative Commons Attribution 4.0 International License
https://creativecommons.org/licenses/by/4.0/
-->
# Exporting data & graphics {#exporting}
## Saving data
R provides a variety of options for saving dataframes that have been created. For these examples, we will look at CSV and Excel files, but there are many other options.
### Writing a CSV file
Write the Canada records from gapminder as a CSV file. This example uses the `write_csv()` function that is within the {readr} package.
* ["Write a data frame to a delimited file"](https://readr.tidyverse.org/reference/write_delim.html), from the {readr} package site
```{r setup_571, eval=FALSE}
library(readr)
library(gapminder)
```
Filter so that only the records for Canada are included; assign to new object "gapminder_canada"
```{r}
gapminder_canada <- gapminder |>
filter(country == "Canada")
```
Write the dataframe object as a csv file.
```
write_csv(gapminder_canada, "gm_canada.csv")
```
## Writing an Excel file
{openxlsx}: Read, Write and Edit xlsx Files
* CRAN https://cran.r-project.org/web/packages/openxlsx/index.html
* package reference page: https://ycphs.github.io/openxlsx/
From the Introduction article at the package reference: https://ycphs.github.io/openxlsx/articles/Introduction.html
## Saving graphs
`ggsave()` (one of the functions in {ggplot2})
https://ggplot2.tidyverse.org/reference/ggsave.html
Let's make a plot of life expectancy changes in Canada, using the dataframe we made above:
```{r}
plot_gm_canada <- ggplot(gapminder_canada, aes(x = year, y = lifeExp)) +
geom_line()
plot_gm_canada
```
To save this plot as a separate file, we can use the `ggsave()` function. Note that in this example, the image hasn't been saved into our environment as a plot object--the `ggsave()` function will save the last object that was created. In this version, we save the previously created plot as a png file.
```
ggsave("gapminder_canada_lifeexp.png")
```
The function has arguments that you might find useful:
* specify the file type,
* specify an object, and
* the change the dimensions to suit your purpose and data:
```
ggsave("gapminder_canada_lifeexp.jpg",
plot_gm_canada,
width = 9, height = 6)
```