library(chatgpt)14 R and Generative AI
14.1 An Introduction Using the ChatGPT R Package
Install the ‘chatgpt’ package and attach the library to your R session. ‘OpenAI’s ’ChatGPT’ https://chat.openai.com/ coding assistant for ‘RStudio’. A set of functions and ‘RStudio’ addins that aim to help the R developer in tedious coding tasks.
First you will need to obtain your ChatGPT API key. You can create an API key by accessing OpenAI API page.
Then you have to assign your API key for usage in R, this can be done just for the actual session, by doing:
Sys.setenv(OPENAI_API_KEY = "XX-XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX")Reference:
?chatgpt14.2 Examples:
Ask questions:
cat(ask_chatgpt("What do you think about R language?"))Comments:
cat(ask_chatgpt("}
cat(comment_code("for (i in 1:10) {\n print(i ** 2)\n}"))Complete code:
cat(ask_chatgpt("}
cat(complete_code("# A function to square each element of a vector\nsquare_each <- function("))Create variables:
cat(ask_chatgpt("}
cat(create_variable_name("sapply(1:10, function(i) i ** 2)"))Explain code:
cat(ask_chatgpt("}
cat(explain_code("for (i in 1:10) {\n print(i ** 2)\n}"))Find issues in code:
cat(ask_chatgpt("}
cat(find_issues_in_code("i <- 0\nwhile (i < 0) {\n i <- i - 1\n}"))Optimize code:
cat(ask_chatgpt("}
cat(find_issues_in_code("i <- 0\nwhile (i < 0) {\n i <- i - 1\n}"))Refactor code:
cat(ask_chatgpt("}
cat(refactor_code("i <- 10\nwhile (i > 0) {\n i <- i - 1\n print(i)\n}"))