![](../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 Analysis Exercises

Import Tidyverse:

```{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_11_data_analysis_solutions.Rmd)

> In order to compare the analysis in R with Excel, the exercises where kept as similar as possible. 

### Exercise 1

Import the [Mice Protein Expression ](https://www.kaggle.com/datasets/ruslankl/mice-protein-expression?resource=download) dataset in R. It contains data on the levels of protein expression of mice proteins in different mice.
Perform the following calculations on this data frame and display them as a table:  

- Calculate the minimum, maximum, average, median from the columns `CDK5_N` and `Tau_N`. Display the answers in a data frame.  

```{r}
file_path <- "./files_10_data_analysis_exercises/exercise01/Data_Cortex_Nuclear.csv"
df <- read_csv(file_path)
formatted_table(head(df))
```

The calculations of the minimum, maximum, average and median of these two proteins:
```{r}
min_CDK5_N <- min(df$CDK5_N)
max_CDK5_N <- max(df$CDK5_N)
mean_CDK5_N <- mean(df$CDK5_N)
median_CDK5_N <- median(df$CDK5_N)

min_Tau_N <- min(df$Tau_N)
max_Tau_N <- max(df$Tau_N)
mean_Tau_N <- mean(df$Tau_N)
median_Tau_N <- median(df$Tau_N)

results_ex1 <- tibble("measure" = c("minimum", "maximum", "mean", "median"), 
                      "CDK5_N" = c(min_CDK5_N, max_CDK5_N, mean_CDK5_N, median_CDK5_N),
                      "Tau_N" = c(min_Tau_N, max_Tau_N, mean_Tau_N, median_Tau_N)
                      )

formatted_table(results_ex1)
```

### Exercise 2

Index, filter and sort your data frame to answer the following questions:  
1. Which mouse has the highest expression of the Tau protein?  
2. What is the relative expression value of this protein in this particular mouse?  
3. Which mouse has the lowest expression of the pAKT protein?  
4. How many empty cells (`NA`) are in the BAD column? Use the `summary` function to find the amount of empty cells.  
5. Which mouse of the Ts65Dn genotype group has the highest Tau expression (use multi-sorting)?  
6. Which mouse of the Ts65Dn genotype, and saline treatment group has the highest Tau expression (use multi-sorting)?  

Mouse with the highest expression of the protein `Tau_N`:  

```{r}
df %>%
  filter(`Tau_N` == max(df$Tau_N)) %>%
  formatted_table()
```


The relative expression value for this protein in this particular mouse.
First, we need to find in which row the maximum value for the highest expression of the Tau protein is stored. First we calculate the max value for this column:  
```{r}
max(df$Tau_N)
```
Then we create a logical factor to match the highest number.  

```{r}
head(df$Tau_N == max(df$Tau_N)) # Somewhere the value will be TRUE
```


Then we can search in the data frame for the row that matches the logical.  

```{r}
df[df$Tau_N == max(df$Tau_N), ]
```

Or tidyverse style:

```{r}
df %>%
  slice_max(Tau_N) %>%
  formatted_table()
```


Mouse with the lowest expression of the pAKT protein. There are NA values in this column, so will have to use the `na.rm =` argument in the calculation:

```{r}
formatted_table(filter(df, `pAKT_N` == min(df$pAKT_N, na.rm = TRUE))) # this will remove all NA values and then show the mouse with minimal value for pAKT
```

Or tidyverse style:

```{r}
df %>%
  slice_min(pAKT_N) %>%
  formatted_table()
```


Amount of empty cells (`NA`) in the BAD column: 

```{r}
summary(df$BAD_N)
```
The amount of empty cells is in the last column.

Or:

```{r}
sum(is.na(df$BAD_N))
```


Mouse of the Ts65Dn genotype group with the highest Tau expression:  

```{r}
df %>% 
  arrange(desc(Genotype), desc(Tau_N)) %>%
  slice_head(n = 6) %>%
  formatted_table()
```

Or to filter for the row:

```{r}
my_answer <- df %>% 
  filter(Genotype == "Ts65Dn") %>%
  filter(Tau_N == max(Tau_N, na.rm = T))
formatted_table(my_answer)
```


Mouse of the Ts65Dn genotype, and saline treatment group with the highest Tau expression (use multi-sorting):  

```{r}
df %>% 
  arrange(desc(Genotype), desc(Treatment), desc(Tau_N)) %>%
  slice_head(n = 6) %>%
  formatted_table()
```
Or to filter for the row:  

```{r}
my_answer <- df %>% 
  filter(Genotype == "Ts65Dn") %>%
  filter(Treatment == "Saline") %>%
  filter(Tau_N == max(Tau_N, na.rm = T))
formatted_table(my_answer)
```


### Exercise 3

1. An relative expression level > 0.5 would be considered a high expression level. How many mice do have a high expression level for DYRK1A?  
2. Apply this calculation for all proteins. For which protein do you observe a count of 218? Hint: you can calculate the mean and the sum for multiple columns at once with the `colMeans` and `colSums` functions.  
3. The average pELK expression is higher than pERK. But how many mice do have higher expression levels for pELK than 0.75 AND higher expression levels for pERK than 0.25?  

You can use the `sum` function to count how many times the value for DYRK1A is higher than 0.5. However, there are NA values in this column, so you will have to use the `na.rm =` argument in the `sum` function.  

```{r}
summary(df$DYRK1A_N) # to check whether there NA values in this column
print("Yes, there are 3 NA values in this column!")

sum(df$DYRK1A_N > 0.5, na.rm = TRUE)
```

Note: the `nrow` function does not work in this case, because it will include the rows with `NA` values. Compare with the previous answer:
```{r}
nrow(df[df$DYRK1A_N > 0.5, ])
```

The protein that has a higher relative expression value than 0.5 in 218 mice.
```{r}
only_nums <- select_if(df, is.numeric) # select only columns with numeric values
colSums(only_nums > 0.5, na.rm = TRUE)
```

Or in tidyverse style:

```{r}
df %>%
  summarise(
    across(
      .cols = where(is.numeric),
      .fns = ~ sum(. > 0.5, na.rm = TRUE)
    )
  )
```


Also here, you can use the `sum` function to count how many times the value for pELK is higher than 0.75 anf for pERK is lower than 0.25.

```{r}
sum(df$pELK_N > 0.75 & df$pERK_N > 0.25, na.rm = T)
```


### Exersise 4

> Note that this exercise differs a bit from the Excel counterpart. We do not use conditional formatting but selection of rows instead.  

1. Select rows with a relative expression value higher than 2.3 for the pCASP9 protein. Which treatment is mostly found for these selected proteins?  
2. Select rows with duplicate MouseIDs. Are there any duplicate MouseIDs?  
3. Select the following columns: MouseID, APP_N, NR1_N, pCREB_N, S6_N, and Genotype.  
4. Select everything but the columns with relative expression measurements. Hint: the column names of the column with relative expression values all have something in common.   

Select rows with a relative expression value higher than 2.3 for the pCASP9 protein:  

```{r}
df %>%
  filter(pCASP9_N > 2.3) %>%
  formatted_table()
```
It seems that in this selection of mice most are treated with Saline.

Select rows with duplicate MouseIDs. Are there any duplicate MouseIDs?  

```{r}
df %>%
  group_by(MouseID) %>%
  filter(n() > 1)
```

There are no duplicates!

Select the following columns: MouseID, APP_N, NR1_N, pCREB_N, S6_N, and Genotype. 

```{r}
df %>% 
  select(MouseID, APP_N, NR1_N, pCREB_N, S6_N, Genotype) %>%
  slice_head(n = 6) %>%
  formatted_table()
```

Select everything but the columns with relative expression measurements.  

```{r}
df %>%
  select(-ends_with("_N")) %>%
  slice_head(n = 6) %>%
  formatted_table()
```


### Exercise 5

> Note that this exercise differs a bit from the Excel counterpart. We do not use a pivot table but the results will be similar.  

Group the genotypes of the mice.  
Calculate the standard deviation, average and the median of the relative expression of the following genes:
- PKCA  
- RRP1  
- BRAF  
- JNK  

Round the values to 3 decimals.  

First, check whether the columns contain `NA` values:
```{r}
proteins <- c("PKCA_N", "RRP1_N", "BRAF_N", "JNK_N") # make a selection of columns to check if there are NA values
summary(df[proteins]) # check the selected columns for NA values
```

The summary gives the mean and median for these proteins. However, this is the mean and median for all measurements (not for the groups (Saline en Memantine treated) that we are interested in)
It seems that only the column of the RRP1 protein does not contain `NA` values. This means that we have to use the `na.rm =` argument to calculate the standard deviation for the other three proteins:
```{r}
df %>%
    group_by(Genotype) %>%
    summarize("St.Dev PKCA" = round(sd(PKCA_N, na.rm = T), 3),
              "Mean PKCA" = round(mean(PKCA_N, na.rm = T), 3),
              "Median PKCA" = round(median(PKCA_N, na.rm = T), 3),
              "SD.Dev RRP1" = round(sd(RRP1_N), 3),
              "Mean RRP1" = round(mean(RRP1_N, na.rm = T), 3),
              "Median RRP1" = round(median(RRP1_N, na.rm = T), 3),
              "SD.Dev BRAF" = round(sd(BRAF_N, na.rm = T), 3),
              "Mean BRAF" = round(mean(BRAF_N, na.rm = T), 3),
              "Median BRAF" = round(median(BRAF_N, na.rm = T), 3),
              "SD.Dev JNK" = round(sd(JNK_N, na.rm = T), 3),
              "Mean JNK" = round(mean(JNK_N, na.rm = T), 3),
              "Median JNK" = round(median(JNK_N, na.rm = T), 3)
              ) %>%
  formatted_table()
```

---

[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.

