Skip to content

Instantly share code, notes, and snippets.

@graebnerc
Created May 8, 2025 18:34
Show Gist options
  • Select an option

  • Save graebnerc/f4a4822676d81f5f608b1a9c4648614f to your computer and use it in GitHub Desktop.

Select an option

Save graebnerc/f4a4822676d81f5f608b1a9c4648614f to your computer and use it in GitHub Desktop.
Base code for exercises of the session on "AI for coding".
This is the code from which you can start working on the exercises of the session on "AI for coding".
# This function is supposed to calculate the median of a numeric vector
# after removing NA values, but it has an error
calculate_median <- function(x) {
# Remove NA values
clean_data <- na.omit(x)
# Sort the data
sorted_data <- sorted(clean_data)
# Calculate the median
n <- length(sorted_data)
if (n %% 2 is 1) {
# Odd number of elements
median_value <- sorted_data[(n + 1 / 2]
} else {
# Even number of elements
median_value <- (sorted_data[n / 2] + sorted_data[(n / 2) - 1]) / 2
}
return(median_value)
}
# Test data
test_vector <- c(5, 2, NA, 9, 1, NA, 3)
result <- calculate_median(test_vector)
print(result)
# This function needs proper documentation
analyze_sales_data <- function(sales, dates, categories, min_value = 0) {
valid_idx <- which(sales > min_value)
sales <- sales[valid_idx]
dates <- dates[valid_idx]
categories <- categories[valid_idx]
total_sales <- sum(sales)
avg_sales <- mean(sales)
sales_by_category <- tapply(sales, categories, sum)
dates <- as.Date(dates)
monthly_sales <- tapply(sales, format(dates, "%Y-%m"), sum)
yearly_trend <- tapply(sales, format(dates, "%Y"), mean)
result <- list(
total = total_sales,
average = avg_sales,
by_category = sales_by_category,
monthly = monthly_sales,
yearly_trend = yearly_trend
)
return(result)
}
# Example usage
sales <- c(120, 250, 30, 45, 190, 320, 15, 80)
dates <- c("2023-01-15", "2023-01-28", "2023-02-10", "2023-02-22",
"2023-03-05", "2023-03-18", "2023-04-02", "2023-04-15")
categories <- c("Electronics", "Furniture", "Clothing", "Electronics",
"Furniture", "Electronics", "Clothing", "Clothing")
results <- analyze_sales_data(sales, dates, categories)
# This function calculates the cumulative sum of squares for values in a vector
# It works correctly but is very inefficient for large vectors
slow_cumulative_sum_squares <- function(vector) {
result <- numeric(length(vector))
for (i in 1:length(vector)) {
sum_squares <- 0
for (j in 1:i) {
sum_squares <- sum_squares + vector[j]^2
}
result[i] <- sum_squares
}
return(result)
}
# Test with a small vector
small_test <- c(1, 2, 3, 4, 5)
result_small <- slow_cumulative_sum_squares(small_test)
print(result_small)
# This would be very slow with a large vector
# large_test <- rnorm(10000)
# system.time(result_large <- slow_cumulative_sum_squares(large_test))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment