Skip to content

Instantly share code, notes, and snippets.

@fkeck
Created March 28, 2023 18:18
Show Gist options
  • Select an option

  • Save fkeck/05b28c9f90f030fd1f1baa4ed637b92e to your computer and use it in GitHub Desktop.

Select an option

Save fkeck/05b28c9f90f030fd1f1baa4ed637b92e to your computer and use it in GitHub Desktop.
Experiment with ChatGPT to generate R code from natural language
describe_data_df <- function(x) {
res_1 <- paste0("data is a dataframe with ", ncol(x), " colums", ":")
res_2 <- sapply(x, class)
res_2 <- sapply(1:length(res_2), function(x) {
paste0("- Column ", x, " is named '", names(res_2)[x], "' and is of class ", res_2[x], ".")
})
res_2 <- paste(res_2, collapse = "\n")
res <- paste(res_1, res_2, sep = "\n")
return(res)
}
gpt_do <- function(data, prompt) {
Sys.setenv(OPENAI_VERBOSE = FALSE)
Sys.setenv(OPENAI_MODEL = "text-davinci-003")
Sys.setenv(OPENAI_TEMPERATURE = 0)
if(!is.data.frame(data)) {
stop("data is not a dataframe.")
}
gpt_prompt <- paste0(describe_data_df(data),
prompt,
"Put the result in an object called 'res'",
"Return only the code, do not comment or explain.",
sep = "\n")
gpt_code <- chatgpt::ask_chatgpt(gpt_prompt)
cat(gpt_code)
eval(parse(text = gpt_code))
return(res)
}
# DEMO
library(tidyverse)
# Set your OpenAI API key here
Sys.setenv(OPENAI_API_KEY = "XXXXXXXXXXXXXXXXXXXXXXXXXXXX")
palmerpenguins::penguins %>%
gpt_do("Use dplyr to add a new variable bill_product by multiplying bill_length_mm by bill_depth_mm") %>%
filter(!is.na(sex)) %>%
gpt_do("Make a scatterplot with ggplot showing the relationship between bill_product and body_mass_g.
Create a panel for each sex. Use a bright theme. Rewrite the axis labels")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment