如何自动循环调用case_importer函数遍历澳高院年度判例
Great question—let's streamline your process so you never have to manually adjust loop counts again, while also cleaning up how you store your data (goodbye scattered global lists!).
First: Fix the cases_in_year Function for Reliability
Your current version uses a hardcoded index (year - 1947) which will break if your Excel file ever has non-consecutive years. Let's make it more robust with dplyr:
cases_in_year <- function(year) { hc_cases_per_year %>% filter(year == .env$year) %>% pull(num_cases) %>% as.integer() }
Option 1: Base R Approach (No Extra Packages Needed)
Instead of creating individual global lists for each year, use a single named list to store all your data. This keeps your environment tidy and makes it easier to iterate over:
# Initialize a single named list to hold all year-specific case data all_hc_cases <- list() # Loop through every year in your Excel dataset for (year in hc_cases_per_year$year) { # Get the number of cases for the current year total_cases <- cases_in_year(year) # Use lapply to import all cases for this year all_hc_cases[[as.character(year)]] <- lapply(1:total_cases, function(case_num) { case_importer(year, case_num) }) }
Option 2: Tidyverse/Purrr Approach (More Concise)
If you prefer the tidyverse style, purrr::map2 lets you pair years with their case counts and import everything in a single pipeline:
library(purrr) library(tibble) # Create a named list of case data, where names are years all_hc_cases <- hc_cases_per_year %>% mutate( # Import all cases for each year using map2 to pair year + case count case_data = map2(year, num_cases, ~lapply(1:.y, case_importer, year = .x)) ) %>% select(year, case_data) %>% deframe() # Convert to a named list (year names -> case data lists)
Convert Lists to Dataframes (Automated)
To turn each year's case list into a dataframe (using your list_to_df function), just add one more step:
# Base R version all_hc_cases_dfs <- lapply(all_hc_cases, list_to_df) # Tidyverse version all_hc_cases_dfs <- map(all_hc_cases, list_to_df)
Why This Works Better
- No manual loop adjustments: The code automatically pulls case counts from your Excel file, so you never have to update numbers manually.
- Cleaner environment: Instead of 70+ global lists (1948-2020), you have one or two centralized lists to manage.
- Robustness: The updated
cases_in_yearfunction works even if your Excel file has missing years or is out of order.
内容的提问来源于stack exchange,提问作者Jordan Rothwell

