## R and Rstudio

-   R: programming software
-   Open R once to look at it - you will never need this again
-   Rstudio: text and code editor, file manager - program in which you actually work
-   You could also use other environments (e.g. Jupyter Notebooks, Visual Studio Code)

## RStudio interface

```{r}
#| echo: false
#| fig-width: 10
knitr::include_graphics("images/Rstudio_interface.png")
```

::: aside
-   Left top = Source pane: Writing your scripts (with code & text)
-   Left bottom = Console: executing code directly
-   Right pane = information about your code, outputs of your code, help...
:::

## Console commands

- Let's start working in the Console. 

```{r}
1 + 1
```

-   History of commands: up/down arrows
-   Entries can have multiple lines
-   Lines starting with \# are a **comment**: notes that explain what your code is doing. Comments are crucial for reproducibility, and for making the life of your later self easier.

```{r}
# let's break it over multiple lines
1 + 2 + 3 + 4 + 5 + 6 +
    7 + 8 + 9 +
    10
```

-   `>` at the start of a line: R is waiting for a new line
-   `+`: R waits until you finish a command from the previous line

```{r}
(3 + 2) * #enter only this part first: # R waits until next line for evaluation
     5
```

## Coding Terms

### Objects & Assignment

-   Objects = variables: store results, numbers, letters for later use
-   Assigning something to an object: storing it

```{r}
## use the assignment operator '<-'
## R stores the number in the object
x <- 5
```

Use the object x in your next step:

```{r}
x * 2
```

**Valid object names**

-   Object starts with a letter or a full stop and a letter

-   Object distinguishes uppercase and lowercase letters

-   Valid objects: songdata, SongData, song_data, song.data, .song.data, never_gonna_give_you_up_never_gonna_let_you_down

-   Invalid objects: \_song_data, 1song, .1song, song data, song-data

::: callout-caution
## Exercise

Which of the following are valid object names?

1.  `slender_man`\
2.  `copy pasta`\
3.  `DOGE`\
4.  `(╯°□°）╯︵ ┻━┻`\
5.  `ErMahGerd`\
6.  `34Rule`\
7.  `panik-kalm-panik`\
8.  `👀`\
9.  `I_am_once_again_asking_you_for_your_support`\
10. `.this.is.fine.`\
11. `_is_this_a_pigeon_`
:::

### Strings

-   Text inside quotes is called a **string**, here one assigned to an object called "string1":

```{r}
string1 <-"I am a string"
```

You can break up text over multiple lines; R waits for a close quote. If you want to include quotes inside this string, escape it with a backslash.

```{r}
long_string <- "In the grand kingdom of Punctuation, the 
exclamation mark and the question mark decided 

to throw a party. They invited all the punctuation marks: 
the commas, the semicolons, the colons, and even the ellipsis. 
The period, known for being a bit of a downer, said, 

\"I'll stop by.\""

cat(long_string) # cat() prints the string
```

### The environment

![](images/environment.png)

-   When you assign something to an object, R creates an entry in the global environment.
-   Saved until you close Rstudio
-   Check the upper right pane
-   Click the broom icon to clear all objects
-   Useful functions:

```{r}
ls()            # print the objects in the global environment
rm("x")         # remove the object named x from the global environment
rm(list = ls()) # clear out the global environment
```

### Whitespace

R mostly ignores them. Use them to organize your code.

```{r}
# a and b are identical
a <- list(ctl = "Control Condition", exp1 = "Experimental Condition 1", exp2 = "Experimental Condition 2")

# but b is much easier to read
b <- list(ctl  = "Control Condition",
          exp1 = "Experimental Condition 1",
          exp2 = "Experimental Condition 2")
```

It is often useful to break up long functions onto several lines.

```{r}
cat("The hyphen and the dash argued about who was faster to get there.",
    "The parentheses brought their side comments,",
    "while the quotation marks couldn't stop", 
    "repeating what everyone else said.",
    sep = "  \n") #start a new line after each comma/element
```

### Function syntax

-   **Function**: code that can be reused
-   Example: `sd` to calculate the standard deviation
-   Functions are set up like this:

```{r, eval = FALSE}
function_name(argument1, argument2 = "value")
```

- Arguments can be named: (argument1 = 10)
- You can skip the names if you put the arguments in the order defined in the function.
- Example with an invented function that assigns people (values) to seats (arguments): Maria gets seat 1, Barbara seat 2 and Claudia seat 3. 

With names the order does not matter: 
```{r, eval = FALSE}
Assign_a_seat(seat3 = Claudia, seat1 = Maria, seat2 = Barbara)
```

You can leave out the names if you put them in the right order. 
```{r, eval = FALSE}
Assign_a_seat(Maria, Barbara, Claudia)
```

-   Check the order in the help pane by typing `?sd` in the console.
-   You can skip arguments that have a default value specified (`FALSE` for `sd`), if the default is what you want. 

::: callout-caution
## Exercise

The function `rnorm()` generates random numbers from the standard normal distribution.

-   Check its syntax in the help page.
    -   what is n?
    -   what is the default mean and sd of the distribution?
-   Try executing the function without any arguments. Why do you get an error?

:::

If you want 10 random numbers from a normal distribution with a mean of 0 and standard deviation of 1, you can just use the defaults.

```{r rnorm-10}
rnorm(10)
```

If you want 10 numbers from a normal distribution with a mean of 100 (we do not need argument names here):

```{r rnorm-10-100}
rnorm(10, 100)
```

This gives you the same result, it's just less efficient for writing: 

```{r rnorm-n-10-m-100}
rnorm(n = 10, mean = 100)
```

We need names if we change the third argument, without writing out the second: 

```{r rnorm-10-sd-100}
rnorm(10, sd = 100)
```

Functions with a list of options after an argument: the default value is the first option. The function `power.t.test()` helps you make calculations around statistical power of t-tests. Its help entry looks like this:

```{r, eval = FALSE}
power.t.test(n = NULL, delta = NULL, sd = 1, sig.level = 0.05,
             power = NULL,
             type = c("two.sample", "one.sample", "paired"),
             alternative = c("two.sided", "one.sided"),
             strict = FALSE, tol = .Machine$double.eps^0.25)
```

What about the `NULL`s? More info from the help entry: 

- Two of the arguments with `NULL` need to be specified (no defaults). The third is calculated. 
  - n: number of observations per group
  - delta: true difference in means
  - power: power of test
  

::: callout-caution
## Exercise

-   What is the default value for sd?
-   What is the default value for type?
-   Which is equivalent to power.t.test(100, 0.5)?
    1.  power.t.test()
    2.  power.t.test(n = 100)
    3.  power.t.test(delta = 0.5, n = 100)
    4.  power.t.test(100, 0.5, sig.level = 1, sd = 0.05)
    
:::

## Add-on packages

-   Package: Collection of code somebody has written and shared
    -   Examples: data visualisation, machine learning, web scraping, neuroimaging...
-   Main repository: CRAN, the Comprehensive R Archive Network

### Installing and loading

1.  Installing: Only once (like an app). Always from the console (not from a script).

```{r, eval=FALSE}
# type this in the console pane
install.packages("beepr")
```

2. Loading a package (like opening an app)

```{r}
library(beepr)
```

Now you can run the function `beep()` from the package. Turn on your sound before you do. 

```{r beepr-demo, eval = FALSE}
beepr::beep() # default sound
beepr::beep(sound = "mario") # change the sound argument
```

For clean code: Use `package::function()` to indicate which package a function comes from.

-   `readr::read_csv()` refers to
    -   the function `read_csv()`
    -   in the package `"readr"`

### Tidyverse

`"tidyverse"`is a meta-package that loads several packages we'll be using in almost every script:

-   `ggplot2` for data visualisation

-   `readr` for data import

-   `tibble` for tables

-   `tidyr` for data tidying

-   `dplyr` for data manipulation

-   `purrr` for repeating things

-   `stringr` for strings

-   `forcats` for factors (categorical variables)

::: callout-caution
## Exercise

-   Install Tidyverse via your console.
-   Check installed and loaded packages in the lower right pane.

```{r, echo=FALSE}
knitr::include_graphics("images/right_pane_packages.png")
```
:::

<!-- ### Install package from GitHub -->

<!-- -   Some packages still under development are not yet on CRAN. -->

<!-- -   Install the package {devtools} to be able to download packages from GitHub -->

<!-- -   Check if devtools is installed by trying to load it. What does the error say? -->

<!-- ```{r, eval=FALSE} -->

<!-- # Install devtools:  -->

<!-- install.packages("devtools") -->

<!-- ``` -->

<!-- Now you can install packages from Github (here the package for our free online course): -->

<!-- ```{r, eval=FALSE} -->

<!-- devtools::install_github("psyteachr/reprores-v3") -->

<!-- ``` -->

## Getting help

-   It's normal to look things up all the time!
-   Very useful: [Cheatsheets](https://posit.co/resources/cheatsheets/)
    -   Access via `Help` -\> `Cheatsheets`
    -   For today: [RStudio IDE Cheatsheet](https://rstudio.github.io/cheatsheets/rstudio-ide.pdf)

### Function help

```{r}
# these methods are all equivalent ways of getting help
help("rnorm")
?rnorm
help("rnorm", package="stats") 
```

Package is not loaded, or you don't know which package the function belongs to: Use `??function_name`.

### Googling

- Using jargon like "concatenate vectors in R" helps
- You'll get more useful results with practice
- Use R, Rstats, or the name of the package.
- [www.rseek.org]() only shows R-specific results

### LLM models (ChatGPT, Claude, Gemini)

- LLM models are really good programmers. 
- They were trained on lot's of code from the internet.
- Some can even execute code (ChatGPT, Claude).
- It helps to know the basics of coding to understand how to use their output. 
- But then, these models make you as good as an average data scientist.
- Checkout [https://hannahmetzler.eu/ai_skills]() for tips about using LLMs.

### Vignettes

-   They explain how to use a package.
-   Many packages have vignettes.

```{r, eval=FALSE}
library(tidyverse)
# open a list of available vignettes for the plotting package ggplot2: 
vignette(package = "ggplot2")

# open a specific vignette in the Help pane
vignette("ggplot2", package = "ggplot2")
```

### Asking for help of human experts

-   If all else fails: Forums like Statsexchange
    -   Copy & paste your code and errors to be precise

## Quick introduction to Git & Github

### What for?

- Back up for your code - never loose your work.
- Version control
- Share code (for students, publications...)
- Collaborate on coding projects
- Use code from multiple computers
- For all files – not just code!

### How does it work?

```{r echo=FALSE}
knitr::include_graphics('images/how_git_works.svg')
```

::: aside
[Image by Jana Lasser](https://github.com/JanaLasser/digitalisation-in-research-module-2/blob/main/03_collaborations/03_02_collaborative_code_writing/slides/img/how_git_works.svg)
:::

### Preparations for next time

-   Set up Git & GitHub on your laptop.
-   Detailed instructions [here](https://hannahmetzler.eu/R_intro/Lesson_2/Install_Git_GitHub/Git_Github.html)

## Optional exercises

### Type commands into the console

In the console, type the following:

```         
1 + 2
a <- 1
b <- 2
a + b
```

Look at the Environment tab in the upper right pane. Set the variable `how_many_objects` below to the number of objects listed in the environment.

```{r}
how_many_objects <- NULL
```

### Understand function syntax

Use the `rnorm()` function to generate 10 random values from a normal distribution with a mean of 800 and a standard deviation of 20, and store the resulting vector in the object `random_vals`.

```{r}
random_vals <- NULL
```

Use the help function to figure out what argument you need to set to ignore `NA` values when calculating the mean of `the_values`. Change the function below to store the mean of `the_values` in the variable `the_mean`.

```{r}
the_values <- c(1,1,1,2,3,4,6,8,9,9, NA) # do not alter this line
the_mean   <- NULL
```

Figure out what the function `seq()` does. Use the function to set `tens` to the vector `c(0, 10, 20, 30, 40, 50 ,60, 70 ,80 ,90, 100)`. Set `bins6` to the cutoffs if you wanted to divide the numbers 0 to 100 into 6 bins. For example, dividing 0 to 100 into 4 bins results in the cutoffs `c(0, 25, 50, 75, 100)`,

```{r}
tens  <- NULL
bins6 <- NULL
```

Figure out how to use the `paste()` function to paste together strings with forward slashes ("/") instead of spaces. Use `paste()` to set `my_dir` to "my/project/directory".

```{r}
my_dir <- NULL
```

### Install a package

Install the CRAN package called "cowsay". Run the code to do this and include it in the code chunk below, but comment it out. It is bad practice to write a script that installs a package without the user having the option to cancel. Also, some packages take a long time to load, so you won't want to install them every time you run a script.

```{r}
# comment out the installation code

```

The code below has errors. Fix the code.

```{r, eval=FALSE}
cowsay::say)
```

```{r, eval=FALSE}
cowsay::say(by = pumpkin)
```

```{r, eval=FALSE}
cowsay::say(by_colour = "blue")
```

### Solutions

Check your solutions [here](https://psyteachr.github.io/reprores-v3/exercises/01_intro_answers.html).

## References

This lesson is based on Chapter 1 Materials and Exercises of this free online text book: Lisa DeBruine & Dale Barr. (2022). [Data Skills for Reproducible Research](https://psyteachr.github.io/reprores-v3/intro.html): (3.0) Zenodo. doi:10.5281/zenodo.6527194.
