Video Notes
To integrate a ChatGPT chat window directly into RStudio we can use a package called chattr.
Get OpenAI API key
To get started, you need to get an API key from OpenAI following these steps:
- Login at https://platform.openai.com/
- Goto Settings (gear icon on top right)
- Find API Keys from menu on left
- Follow the process to Create new secret key
- Copy your secret key (it will only show once so make sure you copy it)
You will need to have some credits loaded on your account in order for chattr to work.
RStudio setup
Next, run the following conmmands in RStudio to initialize chattr - update your-api-key-here
with the API key acquired in the above step.
install.packages("chattr")
library(chattr)
# See https://mlverse.github.io/chattr/#available-models for available models
chattr_use("gpt4")
# Manage keys at https://platform.openai.com/settings/organization/api-keys
Sys.setenv("OPENAI_API_KEY" = "your-api-key-here")
# Setting as_job = TRUE makes the chat app run as a background application, freeing your console up for other work
chattr_app(as_job = TRUE)
After running the above code, you should see a chat window in the Viewer pane where you can issue questions to ChatGPT.
Start Chattr when RStudio loads
If you want to configure RStudio to automatically initialize chatter whenever RStudio is loaded, you can update your .RProfile file.
The .RProfile file is an R startup script that runs every time R or RStudio starts.
To quickly locate/edit the .RProfile file, run the following code:
install.packages("usethis") # Install if not already installed
usethis::edit_r_profile()
With your .RProfile open, enter this code:
# Load chattr app after RStudio is fully loaded
setHook("rstudio.sessionInit", function(newSession) {
if (newSession) {
Sys.sleep(2) # Wait 2 seconds before starting chattr to ensure RStudio is ready
tryCatch({
library(chattr)
chattr_use("gpt4")
Sys.setenv("OPENAI_API_KEY" = "your-api-key-here")
chattr_app(as_job = TRUE)
}, error = function(e)
message("Error starting chattr: ", e$message))
}
}, action = "append")
Save your changes and restart RStudio; after a 2 second delay, you should see the chattr app automatically initializes.
Unlock all notes for $4
For $4, you’ll get 6 months of unlimited access to the notes for the above video
and all of my other 200+ guides and videos.
This is a one-time payment— no subscriptions or auto-renewals to worry about cancelling.
Your support helps me continue creating free, high-quality videos. Thank you!