# RStudio

For Rstudio we recommend using the 'Local Jobs' feature to run jobs in the background. This way you can submit multiple jobs whilst also making sure the job continues to run if you navigate away from Rstudio without blocking the interface.

[Learn more about local jobs in Rstudio](https://github.com/rstudio/webinars/blob/master/74-background-jobs/slides.pdf).

## Recovering an unresponsive RStudio session

In certain cases RStudio sessions can become unresponsive, due to large amounts of output printed or large amount of data loaded. If restarting the application in Nuvolos doesn't resolve the issue, you can follow the steps in the [Application Troubleshooting](/help-and-reference/troubleshooting/application-troubleshooting.md) guide to clear the application state.

## RStudio is responsive but it doesn't accept commands

If the RStudio window is still responsive but commands do not run, check the R console prompt. If the prompt starts with `+` instead of `>`, R is waiting for additional input because the previous command is incomplete, for example due to an unclosed brace, parenthesis, or quote.

To continue, either:

* complete the unfinished expression, or
* click in the R Console and press Escape to cancel it.

## Configuring R Session and RStudio

Upon startup, R and RStudio look for several files to control the behavior of your R session, such as setting options, environment variables, or package repositories.

### User and Project Level Configuration

#### .Rprofile

The `.Rprofile` file contains R code that is executed at the start of every R session. It's commonly used to set options (e.g., `options(digits = 3)`) or load frequently used packages.

* **Location**: Can be in your home directory (`~/.Rprofile`) for global settings or in your project's root directory for project-specific settings.
* **Behavior**: R only sources **one** `.Rprofile` file. If a project-level file exists, it will be used, and the user-level file will be ignored. To use both, you must explicitly source the user-level file at the top of your project-level `.Rprofile`: `source("~/.Rprofile")`.
* **Editing**: You can use `usethis::edit_r_profile()` to edit these files.

#### .Renviron

The `.Renviron` file is used to define environment variables. This is the preferred way to store credentials or API keys instead of hardcoding them in scripts.

* **Format**: Variables are defined in a key-value format: `API_KEY=your_secret_key`.
* **Location**: Like `.Rprofile`, it can be at the user or project level. If a project-level file exists, the user-level one is ignored.
* **Editing**: Use `usethis::edit_r_environ()` to edit.

### System-Wide Configuration

#### Rprofile.site and Renviron.site

These are the system-wide equivalents of `.Rprofile` and `.Renviron`. They are specific to a particular version of R and are usually managed by administrators.

* **Location**: They are located in the `R_HOME/etc/` directory. You can find `R_HOME` by running `R.home(component = "home")` in R.
* **Usage**: Often used to set default package repositories for all users of that R version.

#### rsession.conf and repos.conf

In RStudio Workbench or RStudio Server, administrators can configure server-wide package repositories using these files.

* `rsession.conf`: Used when only one repository is configured.
* `repos.conf`: Used when multiple repositories are needed.

## Using Tensorflow and Keras with RStudio

Tensorflow and Keras can be installed via miniconda in Rstudio. To install them, use the following steps:

1. Restart the R session to be in a clean setting (select Session > Quit Session on the top menu)
2. Make sure reticulate can use miniconda via running in the R commands:

```
Sys.setenv("RETICULATE_MINICONDA_ENABLED" = TRUE)
reticulate::install_miniconda()
```

3\. Install tensorflow R package and then call the `install_tensorflow()` function. If you would like to use GPU acceleration, run `install_tensorflow(version="gpu")`:

```
install.packages("tensorflow") 
library(tensorflow)
install_tensorflow() # use install_tensorflow(version = "gpu") for GPU support
```

4\. Install Keras R package and then call the install\_keras() function:

```
install.packages("keras")
library(keras)
install_keras()
```

To test the installation, follow the example from the RStudio website: <https://tensorflow.rstudio.com/guide/keras/#mnist-example>

### GitHub Copilot with RStudio

Starting with RStudio app version R 4.3.2 with RStudio 2023.09, GitHub Copilot can be configured in Global Options.

To use GitHub Copilot in RStudio:

1. Open Tools > Global Options.
2. Open the GitHub Copilot settings.
3. Sign in with your GitHub account and complete the authorization flow.
4. Confirm that your account has an active GitHub Copilot subscription.

{% hint style="info" %}
GitHub Copilot requires a GitHub account with an active GitHub Copilot subscription. It does not use an OpenAI API key. For OpenAI API-based workflows in RStudio, see the ellmer section instead.
{% endhint %}

## Using ellmer with OpenAI GPT-5.2 and other Large Language Models

The `ellmer` package provides a unified interface for interacting with large language models directly from R, including OpenAI's GPT-5.2. This allows you to leverage AI capabilities for code generation, data analysis assistance, and natural language processing tasks within your RStudio workflow.

### Installation

Install the `ellmer` package from CRAN:

```r
install.packages("ellmer")
library(ellmer)
```

### Configuration with OpenAI API

To use `ellmer` with OpenAI's GPT-5.2 model, you need to provide your API key.

{% hint style="warning" %}
You need an OpenAI API key from a paid OpenAI API account. A ChatGPT subscription is not sufficient - you must create an API key at [platform.openai.com/api-keys](https://platform.openai.com/api-keys).
{% endhint %}

We recommend storing your OpenAI API key as a Nuvolos secret, which will be automatically exposed as an environment variable in your application. See [Environment Variables and Secrets](/features/environment-variables-and-secrets.md) for details on how to set up secrets.

Set up your `OPENAI_API_KEY` as a Nuvolos secret. Once configured, the secret will be available as an environment variable when your RStudio application starts, and `ellmer` will automatically detect it.

### Using ellmer with GPT-5.2

Create a chat object to interact with the GPT-5.2 model:

```r
library(ellmer)

# Set OpenAI API key from Nuvolos secret
Sys.setenv(OPENAI_API_KEY = readLines("/secrets/OPENAI_API_KEY", warn = FALSE))

# Create a chat instance with GPT-5.2
chat <- chat_openai(model = "gpt-5.2")

# Send a message and get a response
chat$chat("How do I create a scatter plot with ggplot2?")

# Continue the conversation with context
chat$chat("Can you add a regression line to that plot?")
```

You can also use `ellmer` for more advanced tasks:

```r
# Generate code completions
chat$chat("Write a function that calculates the mean of a numeric vector, handling NA values")

# Get help with data analysis
chat$chat("I have a dataframe with columns 'age', 'income', and 'education'. 
          What statistical tests should I use to analyze relationships?")

# Use streaming for longer responses
chat <- chat_openai(model = "gpt-5.2", stream = TRUE)
chat$chat("Explain the differences between linear and logistic regression")
```

### Additional Configuration

You can customize the model's behavior with additional parameters:

```r
# Configure temperature, max tokens, and other parameters
chat <- chat_openai(
  model = "gpt-5.2",
  temperature = 0.7,
  max_tokens = 2000,
  system_prompt = "You are an expert R programmer and statistician."
)
```

For more information about `ellmer`, consult the package documentation by running `?ellmer` in R or visiting the package's CRAN page.


---

# Agent Instructions: 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://docs.nuvolos.com/user-guides/application-specific-guides/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.
