> For the complete documentation index, see [llms.txt](https://gitbook.bergelsonlab.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://gitbook.bergelsonlab.com/programming-info/using-git-from-rstudio.md).

# R/RStudio

## How to turn a local R project into a github repo

Here is an R project saved locally, with a .csv file, a .rmd file, and two .r files. I want to create a github repository with all the items in the R project folder.

![](/files/-LJ0RFcq-27fXQcMXW1Y)

Go to [github website](https://github.com/):

1. Click the `New repository` button.
2. Set your new repository name, and click `Create repository` button.
3. Copy the github repository URL from the `Quick setup` chunk.

![](/files/-LJ0RTI1Oz_pRApJhVAE)

Open your local R project in RStudio:

1. click `Tools` -> `Shell…`.
2. Type the following commands in the pop-up window:

   `git init`

   `git add .`

   `git commit -m “first commit”`

   `git remote add origin`` `*`the URL you pasted from github website`*

   `git remote -v`

   `git push origin master`

If you return to Github, all of the items in your local R project folder should be in your repository with the message "first commit".

## How to download someone else's github repo and push a change

* Go to the web link for the GitHub repository you want to work with. Click `Clone or download`, and copy the URL.
* Open RStudio and `File` -> `New Project` -> `Version Control` -> `Git`. Paste the URL copied from GitHub to the `Repository URL`, and click `Create Project`.

![](/files/-LJ0SPvWMkOa81_9omJM)

* After you've created the project, you should be able to open and run the code.

#### Committing changes

After making changes, and before pushing them to the remote github repo, you need to commit them.

Save the file(s) -> click the `Git` tab on the right panel -> select the file(s) you want to commit -> click`Commit` -> make sure the `Staged` button is selected -> add your comment -> and click `Commit`.

![](/files/-LJ0SnNLuRsl_6Mf4e0g)

At this stage, everything is still in your local. To upload your modifications (i.e., your commits) to GitHub so that others can see and pull, you need to push. You can do this by click the `Push` tab. The `Push` tab on the right panel and the `Push` tab on the popup "commit" window are the same. Note: only "commited" changes will be uploaded to GitHub.

![](/files/-LJ0T-_A-_9hO0hHE3IU)

If you are working with others on a project, you'll need to `Pull` their changes to your local copy. Use the down arrow to Pull. This should be the first step you take when you open a shared project. You should also Pull before you Push if you think others have been working on the project.

![](/files/-LJ0TIN4lxoVKZCt5QGh)

### To summarise the workflow

1. from the lab main repo, Click the green “Code” button, copy the URL
2. open RStudio and create the project,&#x20;

   1. Click File → New Project., Select Version Control → Git.,&#x20;
   2. In the Repository URL field, paste the copied URL from GitHub,&#x20;
   3. Choose where to save the project on your computer, Click Create Project.
   4. (in some cases) You will need to authenticate with Personal Access Token (PAT) just to make sure you have access to the repo and can make changes.
   5. verify the clone in the terminal:&#x20;
   6. Open the terminal, type \[git status],&#x20;
   7. you should see the following:&#x20;

   \[On branch main]

   \[Your branch is up to date with 'origin/main'.]
3. (optional, to ensure your local copy stays updated with GitHub): pull change (the downward arrow)
4. Start editing any R scripts and RMD files
5. Once done, open the Git tab, you'll see a list of files in the repo/folder that have undergone some changes
   1. Stage changes (tick/click on each file)
   2. Commit changes (might prompt you to leave a commit note)
   3. Push changes (the upward arrow)
6. Go back to the GitHub repo to see that your changes have been recorded, yay!

{% hint style="info" %}

#### Note: no need to create a new branch, just work under the main branch!

{% endhint %}

### Merge Conflicts

If you hit an error when trying to push your changes ("Updates were rejected because the remote contains work that you do not have locally"), never fear! Merge conflicts may occur if competing changes are made to the same line of a file or when a file is deleted that another person is attempting to edit. You just have to manually fix the conflicts and you'll be good to go.

1. Pull the remote changes. This will fail with a conflict error, but now your file will have both your and the other person's modifications.

![](/files/-LJ0TiHyUVmw7wPyIYyo)

2\. Open the .Rmd and search for "HEAD". This will bring you to the conflict(s), which will look something like this:

3\. Fix the conflict by editing the file as needed. Look over the two versions and decide which is better, or combine the two appropriately. Remove any incorrect text and conflict markers until what's left is ready to knit.

4\. Knit. (This will overwrite the conflicting .pdf and .tex; you do not have to fix those conflicts manually.)

5\. Look over everything to make sure you've fixed all the issues, then stage, commit, and push!

## ggplot blab theme

Use the blab theme! Do it like this:

```
library(tidyverse) # loads ggplot
library(viridis) # loads the color palette you should use for accessible figures
remotes::install_github("BergelsonLab/blabr") 
# makes sure your blabr package is up to date
library(blabr) # loads the package

plotname <- ggplot(mpg, aes(x = cyl, y = displ, colour = class)) + 
  geom_jitter(size = 4)+ # making the dots big to match the plot
  scale_colour_viridis(discrete = T) 
  # using the colour palette I think we should use. 
  # discrete = T/F is an important arg.

plotname

plotname + theme_blab() # you can add theme_blab() to any ggplot

ggsave("path/plotname.tiff", bg = "transparent") 
# your figure will have a transparent background if you keep the bg arg. Try it!
```

## Working with file paths

Paths can be absolute (`/Users/blabber/Documents/data.csv`) or relative (`data.csv`). When you use relative paths, the program needs to know what directory they are relative to. We call that directory (`/Users/blabber/Documents/`) the working directory.

### Knit Directory

When you knit an R-Markdown file in RStudio, you can set the "Knit Directory" - the working directory that will be used when knitting the document. Among other things, every relative path will be considered to be relative to that folder. So, when you write `read_csv('data/penguins.csv')`, R will look for \``data/penguins.csv`\` in that directory.

It can be set to the "Project Directory" (commonly used in BLab), to the "Document Directory" (commonly used outside of BLab) or "Current Working Directory" (at times, useful as a temporary setting). Instead of relying on everyone having "Knit Directory" set to the same option in RStudio, we should define paths in a way that is agnostic to that setting.

### `here` and `fs::path`

One way to do this is to use package `here` and function `fs::path`. We will use `here` to find folders within our project folder and we will use `fs::path` to construct path to files *in relation to these folders*. Like this:

```r
data_folder <- fs::path(here::here('data'))
ant_info <- read_csv(data_folder / 'ant_info.csv')
```

{% hint style="info" %}
Do not use `library(here)` because it prints out the absolute path to the project folder which will be user-specific and will produce unnecessary changes to the knit notebooks.
{% endhint %}


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://gitbook.bergelsonlab.com/programming-info/using-git-from-rstudio.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
