![](../hanze/hanze.png)

---

[Go back to the main page](../index.html)  
[Go back to the R overview page](../R/R_01_index.html)  

---

```{r setup, include=FALSE} 
knitr::opts_chunk$set(warning = FALSE, message = FALSE) 
```

# R

## Data Import Solutions

```{r}
library(tidyverse)
```

>The following function is used to print tibbles in a proper way for the web. You can skip the use of this function to print tibbles to your screen in R Markdown documents.


```{r}
library(knitr)
library(kableExtra)
library(pillar)

formatted_table <- function(df) {
  col_types <- sapply(df, pillar::type_sum)
  new_col_names <- paste0(names(df), "<br>", "<span style='font-weight: normal;'>", col_types, "</span>")
  kbl(df, 
      col.names = new_col_names, 
      escape = FALSE, # This is crucial to allow the <br> tag to work
      format = "html" # Ensure HTML format, although often auto-detected
      ) %>%
    kable_styling(bootstrap_options = c("striped", "hover", "responsive"))
}
```

This file can be downloaded [here](./R_05_data_import_solutions.Rmd).

### Exercise 1

First, check the following files in your text editor (NotePad for Windows users, TextEdit for Apple users). 

- [file 1](./files_04_data_import_exercises/exercise01/fish_data_1.csv)  
- [file 2](./files_04_data_import_exercises/exercise01/fish_data_2.csv)  
- [file 3](./files_04_data_import_exercises/exercise01/fish_data_3.csv)  
- [file 4](./files_04_data_import_exercises/exercise01/fish_data_4.csv)  

Next, report the field separator and the function that you will use to import the data. Also think of you need extra arguments in your function to import the data correctly (for example: do you need the `locale =` argument?).
Last, load the datasets in R using the csv, csv2, or tsv import functionality and check if the data is imported correctly.

**File 1**:  
The field separator used is a comma (,). Therefore use the `read_csv()` function.
```{r}
file_path <- "./files_04_data_import_exercises/exercise01/fish_data_1.csv"
df <- read_csv(file_path)
formatted_table(head(df)) 
```



**File 2**:  
The field separator used is a semi-colon (;). Therefore use the `read_csv2()` function.
```{r}
file_path <- "./files_04_data_import_exercises/exercise01/fish_data_2.csv"
df <- read_csv2(file_path, locale = locale(decimal_mark = "."))
formatted_table(head(df))
```



**File 3**:  
The field separator used is a pipe symbol (|). Therefore use the `read_delim()` function with a `delim =` argument set to the correct delimiter.
```{r}
file_path <- "./files_04_data_import_exercises/exercise01/fish_data_3.csv"
df <- read_delim(file_path, delim="|")
formatted_table(head(df))
```


**File 4**:  
The field separator used is a tab and the decimal separator is a comma. Therefore use the `read_tsv()` function with a `locale =` argument set to the correct decimal separator.

```{r}
file_path <- "./files_04_data_import_exercises/exercise01/fish_data_4.csv"
df <- read_tsv(file_path, locale = locale(decimal_mark = ","))
formatted_table(head(df))
```


### Exercise 2

Download the [Heart Disease Health Indicators](https://www.kaggle.com/datasets/alexteboul/heart-disease-health-indicators-dataset) data set to your computer.
Unzip the file and import the csv data in R.

```{r}
file_path <- "./files_04_data_import_exercises/exercise02/heart_disease_health_indicators_BRFSS2015.csv"
df <- read_csv(file_path)
formatted_table(head(df, c(6,10)))
```



### Exercise 3

Download the [Properties of ATC-accepted medicines](https://www.kaggle.com/datasets/tonibois/properties-of-atc-accepted-medicines) data set to your computer.
Unzip the file and import the csv data in R.

```{r}
file_path <- "./files_04_data_import_exercises/exercise03/KEGG_DRUG_ATC_PROPERTIES_PED_FP.csv"
df <- read_csv(file_path)
formatted_table(head(df, c(6,6)))
```


### Exercise 4

Download the [Food allergens and allergies](https://www.kaggle.com/datasets/boltcutters/food-allergens-and-allergies) data set to your computer.
Unzip the file and import the csv data in R.

```{r}
file_path <- "./files_04_data_import_exercises/exercise04/FoodData.csv"
df <- read_csv(file_path)
formatted_table(head(df))
```

### Exercise 5

Download the [Patients](https://www.kaggle.com/datasets/ouzkoca/patients) data set to your computer.
Unzip the file and import the csv data in R.
NOTE: this file contains the semi-colon as field separator, so you have to use the `read_csv2()` function to read the data correctly.

```{r}
file_path <- "./files_04_data_import_exercises/exercise05/22.11.2021.csv"
df <- read_csv2(file_path)
formatted_table(head(df, c(6, 15)))
```

### Exercise 6

Use R to create a csv file from the following table:

|Protein Name |Location       |Weight (kD)|Date submission |Source       |
|:------------|--------------:|----------:|---------------:|------------:|
| ORF1        | 21571..25392  | 14.3      | 29-FEB-2020    | Published   |
| ORF3a       | 25401..26228  | 23.9      | 29-FEB-2020    | Unpublished |
| ORF4b       | 26253..26480  | 161.1     | 29-FEB-2020    | Unpublished |
| ORF6        | 27210..27395  | 35.9      | 29-FEB-2020    | Submitted   |
| ORF7a       | 27402..27767  | 24.6      | 29-FEB-2020    | Unpublished |


```{r}
protein_name <- c("ORF1", "ORF3a", "ORF4b", "ORF6", "ORF7a")
location <- c("21571..25392", "25401..26228", "26253..26480", "27210..27395", "27402..27767") 
weight <- c(14.3, 23.9, 161.1, 35.9, 24.6)
date_submission <- c("29-FEB-2020", "29-FEB-2020", "29-FEB-2020", "29-FEB-2020", "29-FEB-2020")
ref_source <- c("Published", "Unpublished", "Unpublished", "Submitted", "Unpublished")
my_tibble <- tibble(protein_name, location, weight, date_submission, ref_source)
write_csv(my_tibble, "./files_05_data_import_solutions/exercise06/virus_genome.csv")
```

To prove that the data was written to a csv file:

```{r}
file_path <- "././files_05_data_import_solutions/exercise06/virus_genome.csv"
df <- read_csv(file_path)
formatted_table(head(df))
```

### Exercise 7

Use the same data from exercise 6 but now create an Excel file. Make sure to include the column headers.

```{r}
library(openxlsx)
write.xlsx(my_tibble, "./files_05_data_import_solutions/exercise07/virus_genome.xlsx", colNames = TRUE)
```


### Exercise 8

Use the Excel file from exercise 7 to open the Excel file.

```{r}
library(readxl)
my_data <- read_excel("./files_05_data_import_solutions/exercise07/virus_genome.xlsx")
formatted_table(head(my_data))
```


### Exercise 9


Download the zip file in [this link](./files_05_data_import_solutions/exercise09/read_data_solutions.zip) for the solutions.  

---

[Go back to the main page](../index.html)  
[Go back to the R overview page](../R/R_01_index.html)  
<a href="#top">⬆️ Back to Top</a>  

---


>This web page is distributed under the terms of the Creative Commons Attribution License which permits unrestricted use, distribution, and reproduction in any medium, provided the original author and source are credited.
>Creative Commons License: CC BY-SA 4.0.

