-
Notifications
You must be signed in to change notification settings - Fork 0
/
ppt-5_Read_write.Rmd
75 lines (62 loc) · 1.61 KB
/
ppt-5_Read_write.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
---
title: "Read and write data in R"
author: ""
date: "`r format(Sys.time(), '%d %B, %Y')`"
output:
ioslides_presentation: default
slidy_presentation: default
beamer_presentation: default
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(ggplot2)
```
<style> #slideSty80 > p { margin-top: -80px; } </style>
## Save data {#slideSty80}
- R can save data in different formats
- Data can be saved in R native format
```{r, eval=TRUE}
raptors = c(33,27,26,28)
gsw = c(32, 25, 31, 22)
df = cbind(raptors, gsw)
saveRDS(df, "my_data.rds")
```
- To read it use readRDS function
```{r, eval=TRUE}
mydata = readRDS("my_data.rds")
head(mydata)
```
## Save data {#slideSty80}
- R can save data in CSV formats
```{r, eval=TRUE}
write.csv(df,file="my_data.csv")
```
- To read it use read.csv function
```{r, eval=TRUE}
mydata2 = read.csv("my_data.csv", row.names = 1)
head(mydata2)
```
## Excel files
- R package **openxlsx** can read and write Excel files
- Task: Install the package **openxlsx** and load it
## Write excel files
- To install the package
```{r, eval=FALSE}
install.packages("openxlsx")
```
- To write the Excel file
```{r, eval=TRUE}
library(openxlsx)
write.xlsx(df, "myData.xlsx")
```
- Now open the **myData.xlsx** file, add one more row, save and close the file
## Read excel files
```{r, eval=TRUE}
myxl = read.xlsx("myData.xlsx")
head(myxl)
```
## Caution
- Large Excel files may take long time and memory to read/write
- Use R native **RDS** files to read and write the data during the analysis
- To share data, prefer **CSV** format then Excel
- Save only final results/data in Excel format