## Lab to install R and RStudio

##### Step 1

::: question
Copy and paste the code below into the console pane, and press the <kbd>Enter</kbd> key to run the code. If your installation of R is working correctly, you should see the R version printed out, and a message indicating that your version of R is up do date (like the message seen below).
:::

```{r check_r_version}
#| document: show
r_version_info <- R.Version()
if (all(as.numeric(r_version_info$major) >= 4, 
        as.numeric(r_version_info$minor) > 4
        )
    ) {
  msg <- "✔ Your version of R is up to date!"
} else {
  msg <- "✖ Your version of R is out of date; You should update to version 4.4 now."
}
cat(r_version_info$version.string, msg, sep="\n")
```

##### Step 2

::: question
Copy and paste the R code below into the console and press the <kbd>Enter</kbd> key to run the code. If you have configured RStudio correctly by following the instructions above, you should see a message that says "✔ RStudio is correctly configured!".
:::

```{r unnamed-chunk-2}
#| document: show
rstudio_config <- jsonlite::fromJSON(paste0(rstudio.prefs::rstudio_config_path(),
                                            "/rstudio-prefs.json")
                                     )
options_set <- c(
  rstudio_config$save_workspace == "never",
  rstudio_config$load_workspace == FALSE,
  rstudio_config$restore_last_project == FALSE,
  rstudio_config$restore_source_documents == FALSE,
  rstudio_config$check_for_updates == FALSE,
  rstudio_config$color_preview == FALSE,
  rstudio_config$rmd_viewer_type == "pane",
  rstudio_config$rmd_chunk_output_inline == FALSE
  )

if (all(options_set)) {
  cli::cli_alert_success("RStudio is correctly configured!")
} else {
  cli::cli_alert_danger("RStudio settings have not been correctly configured.")
}
```

##### Step 3

::: question
Copy and paste the R code below into the console and press the <kbd>Enter</kbd> key to run the code. If an appropriate version of the `tidyverse` package is properly installed, you should see two messages: "✔ tidyverse is installed and relatively up-to-date" and "✔ usethis is installed."
:::

```{r check_tidyverse}
#| document: show
has_tidyverse <- suppressPackageStartupMessages(require(tidyverse))
has_usethis <- suppressPackageStartupMessages(require(usethis))

if (has_tidyverse) {
  tidyverse_version <- installed.packages() |>
    as_tibble() |>
    filter(Package == "tidyverse") |>
    pull(Version) 
  
  if (tidyverse_version > 2.0) {
    cli::cli_alert_success("tidyverse is installed and relatively up-to-date.")
  } else {
    cli::cli_alert_danger("tidyverse is installed but it is not up-to-date. Please update your packages.")
  }
} else {
  ui_oops("tidyverse could not be loaded.")
}
if (has_usethis) {
  cli::cli_alert_success("usethis is installed")
} else {
  ui_oops("usethis could not be loaded")
}
```

##### Step 4

::: question
Copy and paste the code below into your R console, and press the <kbd>Enter</kbd> key to run the code. If your project is set up correctly, you should see a message saying "Your project is in a good place" (like the one shown in the image below).
:::

```{r check_project}
#| document: show
project <- tryCatch(
  usethis:::proj_path(),
  error = function(e) {
    if (class(e)[1] == "usethis_error") {
      FALSE
    } else {
      stop(e) # rethrow package not found error!
    }
  }
)

if (!isFALSE(project)) {
  cli::cli_alert_success("Project found at: {.path {project}}. Your project is in a good place.")
} else {
  cli::cli_alert_danger(
    "No project environment detected. Make sure you:\n
     1. Create and open an R project for the course
     2. Move your Quarto file into your project folder before rendering it
    "
  )
}
```

##### Question 5 Create an R script file to submit

-   This question comes from [IDS Chapter 1 Getting started](https://rafalab.dfci.harvard.edu/dsbook-part-1/R/getting-started.html)

::: question
In your course RStudio project folder you just created, add a folder for labs titled "Labs."

**Step 1:** Add a new R script file in RStudio
:::

In the top menu bar, click *File → New File → R Script*

Even though you haven’t written any code yet, you can do a save (File → Save or Command-S on Mac).

Name the file `my-first-script.R`

If you look in the Files pane you’ll now see the new folder listed containing your R script file.

::: question
**Step 2:** Follow the directions and copy and paste the code snippets below into your R Script file.
:::

To add your name and the assignment name/number to the top of your R scripts document:

-   On the first line of the R Script, use `#` followed by the assignment name "Exercise 1".

-   On second line of the R Script, use `#` followed by your name.

Next, type the code below into your R Script file.

Add the code below into your R Script file to install the package that accompanies our primary textbook IDS:

`install.packages("dslabs")`

We can then load the package into our R sessions using the library function:

`library(dslabs)`

Load the tidyverse package:

**`library`**`(tidyverse)`

Load a data set from the `dslabs` package:

`data(murders)`

Last, we'll add code for generating a chart plot:

`murders %>% ggplot(aes(population, total, label = abb, color = region)) + geom_label()`

Make sure you save your file. Then try running it, first by clicking Source (either nothing seems to happen, or you will get a warning because you have already installed the packages in the first few lines of code).

Next, trying to run by *highlighting the code and clicking Run*.

Note that in the lower right you now see the Plots pane with the results of the program.

**What’s the program doing?** Here’s a quick summary, giving you a peek at what we’ll be working on during the next few weeks.

1.  `data(murders)` – this loads the murders data set from the dslabs package. If you look in the Environment pane, you’ll see the data set listed there. And we are told that it has 51 observations (rows) and 5 variables (columns). If you click the little arrow icon to the left of the data set name you’ll get to see a bit more information about the 5 variables. If you double click on the data set name then it actually opens up in a tab in the Edit pane.

2.  `murders %>%` this says that the murders data is what should be used by the next part of the statement.  This is called a “pipe” which we’ll see more soon.

3.  `ggplot(aes(population, total, label = abb, color = region))` calls the ggplot function that we’ll be using to plot data. Without going into too much detail at this point, it basically says that we’re going to plot the data using population as the X-axis value and total murders as the Y-axis value, we’ll label each plot point using the abbreviation column, and we want to color each plot point based on what region of the country the state is in.

4.  `geom_label` There’s a + at the end of the ggplot line which means that the next line will provide additional instructions for the plot. `geom_label` is responsible for drawing the box around the text for each plot point so that it’s easier to read.

See Lab Getting Started instructions and Brightspace for a reminder about what to submit for this exercise.
