Can you write SAS or Python using ChatGPT?
Bil Westerfield Jan. 18, 2023
You've likely heard of ChatGPT. There are numerous articles and blogs online discussing its capabilities. If you have not, it is a chatbot from OpenAI that allows users to type in questions to which ChatGPT provides answers. The bot uses generative AI methods, including both supervised and reinforcement learning, to produce text-based responses. It is designed to be conversational, meaning it answers and often improves responses with additional interaction and dialogue. One task it performs is writing software programs.
Writing SAS Code
Can it be used to write SAS® or Python code? Here at Magpie, we utilize both programming languages to build solutions that help healthcare organizations achieve their analytic objectives. Let's start with a SAS® example and see how ChatGPT performs:
"Write SAS code to determine the average age by gender using the SASHELP.CLASS dataset."
This is probably one of our favorite datasets in the SASHELP library. It is a small 19 observation dataset with five variables: Name, Sex, Age, Height, and Weight. We use this dataset to build examples for clients, staff, and for general testing.
ChatGPT responded with the correct answer:
PROC MEANS DATA=sashelp.class NOPRINT;
CLASS sex;
VAR age;
OUTPUT OUT=age_by_sex MEAN=mean_age;
RUN;
ChatGPT even provided an explanation for the code, which is useful for documenting code:
"This code will create a new dataset called age_by_sex that contains the mean age for each sex in the sashelp.class dataset. The PROC MEANS statement is used to calculate the mean of a continuous variable, and the CLASS statement is used to specify the categorical variable by which the means will be calculated (in this case, sex). The VAR statement specifies the continuous variable for which the means will be calculated (in this case, age). The OUTPUT statement is used to save the results of the PROC MEANS procedure to a new dataset (in this case, age_by_sex), and the MEAN=mean_age option specifies that the mean of the age variable should be stored in a new variable called mean_age."
Writing Python Code
Next, we asked ChatGPT to:
"Write Python code to determine the average Age by Sex using the SASHELP class dataset."
We were curious to see how ChatGPT would answer the question. ChatGPT answered this prompt correctly ignoring a few minor required tweaks. See the code and explanation provided by the bot below:
import pandas as pd
# Load the sashelp.class dataset
df = pd.read_sas("sashelp.class.sas7bdat")
# Calculate the mean age by sex
mean_age_by_sex = df.groupby("sex")["age"].mean()
print(mean_age_by_sex)
The minor changes required were: 1) the first letter in the "Sex" and "Age" variables needed to be capitalized and 2) the local path to "sashelp.class.sas7bdat" needed to be added to the read_sas call.
It was interesting to see ChatGPT utilize the read_sas method, recognizing that a SAS® dataset may be read directly in Python utilizing Pandas. We often utilize this method in projects where we move data back and forth between SAS® and Python - which is a use case we are seeing more and more often.
Advanced Queries
Next, we decided to provide ChatGPT more of a challenge. Here is the next prompt we provided ChatGPT:
"Write SAS code to determine the name of the oldest patient using dataset A with variables Patient ID, Age and dataset B with variables Patient ID, Last Name, First Name."
Below is the initial SAS code that ChatGPT provided:
/* First, merge the two datasets on patient id */
data merged_dataset;
merge dataset_a(in=a) dataset_b(in=b);
by patient_id;
run;
/* Now, sort the merged dataset by age in descending order */
proc sort data=merged_dataset;
by age descending;
run;
/* Finally, use the first observation in the sorted dataset to determine the name of the oldest patient */
data oldest_patient;
set merged_dataset;
by age descending;
if first.age then do;
last_name = last_name; first_name = first_name;
end;
run;
This code is not correct - perhaps we found the limits of ChatGPT. The PROC SORT BY statement applies the DESCENDING option to the variable that follows it, so "Age" and "descending" need to be swapped to avoid a SAS® error. Secondly, ChatGPT's approach will keep the first observation for each age grouping, meaning if there are multiple patients 99 years old and multiple patients 65 years old, it will keep the first observation from each age.
Given this, ChatGPT understood we wanted a more concise code with less steps. Here is its response:
PROC SQL;
SELECT B.last_name, B.first_name
FROM A INNER JOIN B ON A.patient_id = B.patient_id
WHERE A.age = (SELECT MAX(age) FROM A);
QUIT;
This code will select the last name and first name of the patient with the maximum age in dataset A. It does this by performing an inner join between datasets A and B on the patient_id field, selecting only the row with the maximum value of age in dataset A.
Conclusion
So, can we use ChatGPT to write SAS® or Python code? The short answer is yes. However, coders need to be prepared to validate and experiment, especially as the use cases get more and more specific and esoteric. ChatGPT is fallible - so users need to be wary of the bot's responses. Despite this issue, we plan to experiment more with ChatGPT in our daily work.
Finally, when we need a break or a laugh from a long day of coding, we can have fun using ChatGPT by asking it to perform silly tasks such as:
"Write a few lines of Shakespeare about SAS and Python."
"Verse doth deceive, 'tis true, yet here I'll try To spin a tale of SAS and Python's might, Two rivals fierce, in fields of data war, Their skills and tools, a wondrous sight to sight.
SAS doth reign, in mainframe halls of old, A king in age, yet slow to adapt and change, While Python, young and nimble, doth behold A future bright, with ease in range.
Yet SAS is not a has-been, far from it, For still it stands, a fortress, strong and sure, And Python's youth doth not entail a wit Less sharp, less able to endure.
Thus let us not in lies, truth to disguise, But recognize each tool, in its own right, wise."
While ChatGPT may not write quite as well as Shakespeare, it produced a few lines that were good for a quiet laugh before we got back to work for the day.