Created
May 8, 2025 17:38
-
-
Save graebnerc/5bf7f47a92afc22beb63c6fbc1d30831 to your computer and use it in GitHub Desktop.
The prompts used as examples in the slides from the lab on "AI for Coding".
This file contains hidden or 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
| The prompts used as examples in the slides from the lab on "AI for Coding". | |
| Results were created by Claude Sonnet 3.7 in May 2025. |
This file contains hidden or 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
| # Results were created by Claude Sonnet 3.7 in May 2025 | |
| # Prompt:--------------- | |
| # I have written the following function that computes ROI in R: | |
| # | |
| # calculate_roi <- function(revenue, cost) { | |
| # roi <- (revenue - cost) / cost * 100 return(roi) | |
| # } | |
| # | |
| # Please provide a full roxygen2 documentation of the function, including an example. | |
| # Result:--------------- | |
| #' Calculate Return on Investment (ROI) | |
| #' | |
| #' @description | |
| #' Calculates the return on investment as a percentage based on revenue and cost inputs. | |
| #' ROI measures the profitability of an investment relative to its cost. | |
| #' | |
| #' @param revenue Numeric. The total revenue or return generated from the investment. | |
| #' @param cost Numeric. The initial cost or investment amount. Must be non-zero. | |
| #' | |
| #' @return Numeric. The ROI expressed as a percentage. | |
| #' | |
| #' @details | |
| #' The function uses the standard ROI formula: ((revenue - cost) / cost) * 100 | |
| #' A positive result indicates profit, while a negative result indicates loss. | |
| #' | |
| #' @examples | |
| #' # Basic example | |
| #' calculate_roi(150000, 50000) # Returns 200 | |
| #' | |
| #' # Marketing campaign example | |
| #' campaign_revenue <- 75000 | |
| #' campaign_cost <- 25000 | |
| #' campaign_roi <- calculate_roi(campaign_revenue, campaign_cost) # Returns 200 | |
| #' | |
| #' # Investment loss example | |
| #' calculate_roi(8000, 10000) # Returns -20 | |
| #' | |
| #' @export | |
| calculate_roi <- function(revenue, cost) { | |
| roi <- (revenue - cost) / cost * 100 | |
| return(roi) | |
| } |
This file contains hidden or 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
| # Prompt:--------------- | |
| # I am operating in a management context. I use the sales data from above. | |
| # I want to predict future sales using Meta's prophet algorithm. I found the | |
| # following R code that does this. I do not understand this code. | |
| # Please explain it to me step by step. | |
| library(prophet) | |
| library(dplyr) | |
| sales_forecast <- function(data) { | |
| # Rename columns to Prophet's required format | |
| df <- data %>% | |
| rename(ds = quarter_date, y = sales) %>% | |
| select(ds, y) | |
| # Create Prophet model with quarterly seasonality | |
| m <- prophet(df, | |
| seasonality.mode = 'multiplicative', | |
| yearly.seasonality = TRUE, | |
| weekly.seasonality = FALSE, | |
| daily.seasonality = FALSE) | |
| # Add quarterly seasonality | |
| m <- add_seasonality(m, name = 'quarterly', period = 365.25/4, | |
| fourier.order = 5) | |
| # Create future dataframe for 8 quarters ahead | |
| future <- make_future_dataframe(m, periods = 8, freq = 'quarter') | |
| # Make forecast | |
| forecast <- predict(m, future) | |
| # Return results with components | |
| return(list(model = m, | |
| forecast = forecast, | |
| plot = plot(m, forecast), | |
| components = prophet_plot_components(m, forecast))) | |
| } | |
| sales_forecast(sales_clean) | |
| # Example 6: debugging----------- | |
| library(dplyr) | |
| df <- data.frame(id = 1:3, group = factor(c(1, 2, 3))) | |
| filtered_df <- df %>% | |
| filter(group > 1) | |
| print(filtered_df) |
This file contains hidden or 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
| # Results were created by Claude Sonnet 3.7 in May 2025 | |
| # Prompt:--------------- | |
| # Help me in writing R code. Stay within the tidyverse dialect and explain your code using inline comments. | |
| # | |
| # I have a data set on wine: | |
| # alcohol quality residual sugar kind | |
| # 1 8.8 6 20.7 white | |
| # | |
| # Write code that computes average alcohol for all kinds of wine. | |
| # Result:--------------- | |
| library(dplyr) | |
| wine_data <- DataScienceExercises::wine2dine # <- manually added to replace Claude's sample data set | |
| wine_averages <- wine_data %>% | |
| group_by(kind) %>% # Group the data by wine type | |
| summarize( | |
| avg_alcohol = mean(alcohol), # Calculate mean alcohol content | |
| count = n() # Count number of wines in each group | |
| ) |
This file contains hidden or 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
| # Results were created by Claude Sonnet 3.7 in May 2025 | |
| # Prompt:--------------- | |
| # I need to analyze our company's quarterly sales data. I want to do this using R and the tidyverse dialect. But my background is in management studies, not programming. Please provide advice on how I can analyze the data to identify trends and seasonality. | |
| # | |
| # I have the data in the form of a csv file that has the following structure: | |
| # "quarter_date","quarter","sales","region","product_category" | |
| # 2020-01-01,"Q1 2020",12659.86530177,"North","Furniture" | |
| # | |
| # Write R core that: | |
| # * Imports the csv file | |
| # * Cleans the data | |
| # * Create a figure using ggplot2 that highlights trends and seasonality | |
| # Result:--------------- | |
| # Step 1: Load necessary packages | |
| library(readr) # For reading CSV files | |
| library(dplyr) # For data manipulation | |
| library(tidyr) # For data cleaning | |
| library(ggplot2) # For data visualization | |
| library(lubridate) # For handling dates | |
| library(ggpubr) # For arranging multiple plots | |
| # Step 2: Import the CSV file | |
| # Replace "quarterly_sales.csv" with your actual file path if different | |
| sales_data <- read_csv("sales_data.csv") | |
| # Step 3: Examine the data structure | |
| head(sales_data) # View first few rows | |
| summary(sales_data) # Get summary statistics | |
| # Step 4: Clean the data | |
| sales_clean <- sales_data %>% | |
| # Ensure quarter_date is properly formatted as date | |
| mutate(quarter_date = as.Date(quarter_date)) %>% | |
| # Handle missing values in sales column by replacing with mean | |
| mutate(sales = if_else(is.na(sales), | |
| mean(sales, na.rm = TRUE), | |
| sales)) | |
| # Step 5: Create visualizations for trends and seasonality | |
| # 5.1: Overall sales trend over time | |
| trend_plot <- ggplot(sales_clean, aes(x = quarter_date, y = sales)) + | |
| geom_line(color = "blue", size = 1) + | |
| geom_point(color = "darkblue", size = 3) + | |
| geom_smooth(method = "loess", se = FALSE, color = "red", linetype = "dashed") + | |
| labs(title = "Quarterly Sales Trend (2020-2024)", | |
| x = "Quarter", | |
| y = "Sales ($)") + | |
| theme_minimal() + | |
| scale_y_continuous(labels = scales::dollar_format()) + | |
| scale_x_date(date_breaks = "6 months", date_labels = "%b %Y") | |
| # 5.2: Seasonal patterns by extracting quarter | |
| seasonal_plot <- sales_clean %>% | |
| # Extract quarter number (1-4) from date | |
| mutate(quarter_num = lubridate::quarter(quarter_date)) %>% | |
| # Group by quarter to see seasonal patterns | |
| group_by(quarter_num) %>% | |
| summarize(avg_sales = mean(sales, na.rm = TRUE)) %>% | |
| ggplot(aes(x = factor(quarter_num), y = avg_sales)) + | |
| geom_col(fill = "skyblue", width = 0.6) + | |
| geom_text(aes(label = scales::dollar(avg_sales, accuracy = 1)), | |
| vjust = -0.5, size = 3.5) + | |
| labs(title = "Average Sales by Quarter", | |
| x = "Quarter", | |
| y = "Average Sales ($)") + | |
| theme_minimal() + | |
| scale_y_continuous(labels = scales::dollar_format()) | |
| # 5.3: Regional comparison | |
| region_plot <- sales_clean %>% | |
| group_by(region) %>% | |
| summarize(total_sales = sum(sales, na.rm = TRUE)) %>% | |
| ggplot(aes(x = reorder(region, -total_sales), y = total_sales)) + | |
| geom_col(fill = "lightgreen") + | |
| labs(title = "Total Sales by Region", | |
| x = "Region", | |
| y = "Total Sales ($)") + | |
| theme_minimal() + | |
| scale_y_continuous(labels = scales::dollar_format()) | |
| # Step 6: Arrange all plots in one figure with ggpubr::ggarrange() | |
| combined_plot <- ggpubr::ggarrange( | |
| trend_plot, seasonal_plot, region_plot, | |
| ncol = 3, # Stack horizontally | |
| nrow = 1, # Three rows | |
| heights = c(1.2, 1, 1), # Slightly larger height for trend plot | |
| labels = c("A", "B", "C"), # Add labels to each subplot | |
| align = "v" # Align plots vertically | |
| ) | |
| # Add a common title to the combined figure | |
| final_plot <- ggpubr::annotate_figure(combined_plot, | |
| top = ggpubr::text_grob("Quarterly Sales Analysis (2020-2024)", | |
| face = "bold", size = 16), | |
| bottom = ggpubr::text_grob("Source: Company Sales Data", | |
| hjust = 1, x = 1, face = "italic", size = 10) | |
| ) | |
| # Step 7: Save the combined figure as PDF | |
| ggpubr::ggexport( | |
| final_plot, | |
| filename = "sales_analysis.pdf", | |
| width = 16, | |
| height = 5, | |
| dpi = 300 | |
| ) | |
| # Alternatively, you can use ggsave, but ggexport is preferred for ggpubr objects | |
| # ggsave("sales_analysis.pdf", final_plot, width = 10, height = 14) | |
| # Print the combined figure to screen | |
| print(final_plot) |
This file contains hidden or 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
| library(tibble) # For tibble functionality | |
| library(dplyr) # For data manipulation | |
| library(lubridate) # For date handling | |
| library(ggplot2) # For visualization | |
| # Set seed for reproducibility | |
| set.seed(123) | |
| # Create base sales values first | |
| quarter_dates <- seq(as.Date("2020-01-01"), as.Date("2024-10-01"), by = "quarter") | |
| n_quarters <- length(quarter_dates) | |
| # Calculate the sales values with trend, seasonality and noise | |
| base_sales <- 100000 + | |
| (1:n_quarters * 5000) + # Upward trend | |
| (sin(1:n_quarters * pi/2) * 30000) + # Seasonal pattern | |
| rnorm(n_quarters, 0, 15000) # Random noise | |
| # Randomly select some positions to replace with NA | |
| missing_positions <- runif(n_quarters) > 0.9 | |
| base_sales[missing_positions] <- NA_real_ # missing double vector | |
| # Now create the tibble with the pre-calculated sales values | |
| sales_data <- tibble( | |
| # Create quarterly dates | |
| quarter_date = quarter_dates, | |
| # Create quarter labels (Q1 2020, Q2 2020, etc.) | |
| # Using lubridate explicitly with the quarter function | |
| quarter = paste0("Q", lubridate::quarter(quarter_date), " ", lubridate::year(quarter_date)), | |
| # Use the pre-calculated sales values | |
| sales = base_sales, | |
| # Add a region column | |
| region = sample(c("North", "South", "East", "West"), n_quarters, replace = TRUE), | |
| # Add a product category | |
| product_category = sample(c("Electronics", "Furniture", "Clothing", "Office Supplies"), | |
| n_quarters, replace = TRUE) | |
| ) | |
| # Preview the data | |
| head(sales_data) | |
| write.csv(sales_data, "sales_data.csv", row.names = FALSE) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment