Last active
April 16, 2023 11:36
-
-
Save Patrikios/bb19303df830526ebd0632dddefe1987 to your computer and use it in GitHub Desktop.
chatGPT interactions, as well to help you generate and evaluate code
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# an example of using package 'chatgpt' to help you generate pipaeble code | |
# I used here code that I have seen on twitter | |
# however I cannot locate it anymore, no pun intended, will update the sources once I found it | |
# my package loader (installs packages if they are not installed) | |
if (!require(attachee)) { | |
if (!require(devtools)) { | |
install.packages(devtools) | |
} else { | |
install_github("patrikios/attachee") | |
library(attachee) | |
} | |
} | |
# Set your OpenAI API key here | |
sk = "sk-number" # get from chatGPT | |
Sys.setenv(OPENAI_API_KEY = sk) | |
# load the package | |
grab_and_attach(chatgpt) | |
# basic operations | |
cat(ask_chatgpt("What do you think about R language?")) | |
cat(comment_code("for (i in 1:10) {\n print(i ** 2)\n}")) | |
cat(complete_code("# A function to square each element of a vector\nsquare_each <- function(")) | |
# let chat gpt help you coding | |
# seen somewhere online on twitter I think, no pun intended | |
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 | |
grab_and_attach(palmerpenguins, dplyr, ggplot2) | |
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