Certainly! Below is an R function named compute_harvest_means_with_dates that encapsulates the provided code. This function processes harvest data to calculate descriptive statistics, cleans and organizes the results, and joins them with date information from another dataset. Here's a step-by-step breakdown and the complete function implementation:
Function Overview
-
Inputs:
harvest_data: A data frame containing harvest-related variables, including Year, DEC_BASIS, PEO_BASIS, ESL_BASIS, FUT_1, FUT_2, and Crop_Progression.
Harvest_min_max: A data frame containing minimum and maximum date information for each variable by Year.
-
Outputs:
- A tidy data frame (
harvest_means_with_dates) that includes the Year, variable, descriptive statistics (mean, min, max), and corresponding min_date and max_date.
Prerequisites
Make sure you have the necessary packages installed and loaded:
install.packages(c("dplyr", "psych"))
library(dplyr)
library(psych)
Function Implementation
compute_harvest_means_with_dates <- function(harvest_data, Harvest_min_max) {
# Ensure necessary packages are loaded
if (!requireNamespace("dplyr", quietly = TRUE)) {
stop("Package 'dplyr' is required but not installed.")
}
if (!requireNamespace("psych", quietly = TRUE)) {
stop("Package 'psych' is required but not installed.")
}
# Step 1: Calculate descriptive statistics by Year
harvest_stats <- psych::describeBy(
harvest_data %>%
dplyr::select(Year, DEC_BASIS, PEO_BASIS, ESL_BASIS, FUT_1, FUT_2, Crop_Progression),
group = harvest_data$Year,
digits = 2,
mat = TRUE
)
# Step 2: Process stats to extract relevant variables and statistics
harvest_means <- harvest_stats %>%
dplyr::filter(vars %in% c(2, 3, 4, 5, 6, 7)) %>% # Select relevant variables
dplyr::select(item, group1, mean, min, max) %>%
dplyr::mutate(Year = as.numeric(group1)) %>%
dplyr::select(-group1) %>%
dplyr::mutate(
variable = gsub("[0-9]+", "", rownames(.)), # Remove numeric suffixes
variable = dplyr::case_when(
grepl("^FUT_1", rownames(.)) ~ "FUT_1",
grepl("^FUT_2", rownames(.)) ~ "FUT_2",
TRUE ~ variable # Retain existing value for other variables
)
)
# Step 3: Clean variable names to ensure consistency
harvest_means_clean <- harvest_means %>%
dplyr::mutate(variable = dplyr::case_when(
grepl("^DEC_BASIS", variable) ~ "DEC_BASIS",
grepl("^PEO_BASIS", variable) ~ "PEO_BASIS",
grepl("^ESL_BASIS", variable) ~ "ESL_BASIS",
grepl("^FUT_1", variable) ~ "FUT_1",
grepl("^FUT_2", variable) ~ "FUT_2",
grepl("^Crop_Progression", variable) ~ "Crop_Progression",
TRUE ~ variable # Retain existing value if no match
))
# Step 4: Join with Harvest_min_max to get corresponding dates
harvest_means_with_dates <- harvest_means_clean %>%
dplyr::left_join(Harvest_min_max, by = "Year") %>%
dplyr::mutate(
min_date = dplyr::case_when(
variable == "DEC_BASIS" ~ DEC_BASIS_date_min,
variable == "PEO_BASIS" ~ PEO_BASIS_date_min,
variable == "ESL_BASIS" ~ ESL_BASIS_date_min,
variable == "FUT_1" ~ FUT_1_date_min,
variable == "FUT_2" ~ FUT_2_date_min,
variable == "Crop_Progression" ~ Crop_Progression_date_min,
TRUE ~ as.POSIXct(NA) # Assign NA for unmatched variables
),
max_date = dplyr::case_when(
variable == "DEC_BASIS" ~ DEC_BASIS_date_max,
variable == "PEO_BASIS" ~ PEO_BASIS_date_max,
variable == "ESL_BASIS" ~ ESL_BASIS_date_max,
variable == "FUT_1" ~ FUT_1_date_max,
variable == "FUT_2" ~ FUT_2_date_max,
variable == "Crop_Progression" ~ Crop_Progression_date_max,
TRUE ~ as.POSIXct(NA) # Assign NA for unmatched variables
)
) %>%
dplyr::select(Year, variable, mean, min, min_date, max, max_date)
# Step 5: Return the final data frame
return(harvest_means_with_dates)
}
Usage Example
Assuming you have your harvest_data and Harvest_min_max data frames ready, you can use the function as follows:
# Example data frames (replace with your actual data)
# harvest_data <- read.csv("path_to_harvest_data.csv")
# Harvest_min_max <- read.csv("path_to_Harvest_min_max.csv")
# Compute harvest means with dates
result <- compute_harvest_means_with_dates(harvest_data, Harvest_min_max)
# View the result
print(result)
Function Explanation
-
Descriptive Statistics (describeBy):
- The function starts by calculating descriptive statistics (
mean, min, max, etc.) for the selected variables in harvest_data, grouped by Year. This is achieved using the describeBy function from the psych package.
-
Filtering and Selecting Relevant Variables:
- It filters the results to include only the relevant variables (based on their positions; ensure these match your actual data structure).
- It then selects the necessary columns and converts the
group1 column to a numeric Year.
-
Cleaning Variable Names:
- Numeric suffixes are removed from variable names to standardize them.
- Specific patterns in variable names (e.g.,
FUT_1, FUT_2) are handled to ensure consistency.
-
Joining with Date Information:
- The cleaned data is joined with the
Harvest_min_max data frame based on Year.
- For each variable, the corresponding
min_date and max_date are assigned using case_when. If a variable does not match any known patterns, NA is assigned.
-
Final Selection:
- The final data frame includes
Year, variable, mean, min, min_date, max, and max_date.
Notes
-
Error Handling: The function includes checks to ensure that the required packages (dplyr and psych) are installed. If not, it will stop and prompt the user to install them.
-
Flexibility: If the positions of the variables in harvest_stats change, you may need to adjust the filter(vars %in% c(2, 3, 4, 5, 6, 7)) line accordingly.
-
Date Columns: Ensure that Harvest_min_max contains the necessary date columns (e.g., DEC_BASIS_date_min, DEC_BASIS_date_max, etc.) and that they are in POSIXct format or a compatible date-time format.
By encapsulating the code into this function, you streamline the data processing workflow and make it reusable for different datasets or scenarios.