如何在R中逐行传递函数并将结果导出为数据框
Hey there! Let's fix up your approach to this problem—you're right that the current loop has a couple of issues, and we can make this cleaner and more effective with R's functional programming tools.
First, let's spot the problems in your existing loop:
- You're passing the entire
df2todo_reportsevery time instead of the single rowdf2[i,] - You're overwriting
create_reportin each iteration, so you'll only end up with the last run's results instead of saving all of them
Here are a couple of better approaches, starting with base R (no extra packages needed) and then a more concise option with the purrr package:
Base R Solution
We'll use lapply to iterate over each row index of df2, run your function for each row, collect all results in a list, then combine them into final dataframes:
# Step 1: Run do_reports for each row of df2 and collect all results report_results <- lapply(seq_len(nrow(df2)), function(row_idx) { do_reports(df1, df2[row_idx, ], df3) }) # Step 2: Combine all create_report[1] results into one dataframe combined_report1 <- do.call(rbind, lapply(report_results, function(x) x[[1]])) # Step 3: Combine all create_report[2] results into one dataframe combined_report2 <- do.call(rbind, lapply(report_results, function(x) x[[2]]))
Cleaner Solution with purrr (tidyverse)
If you're open to using the purrr package (part of the tidyverse, great for iterative tasks), this code is more readable and concise:
# Install/load purrr if you haven't already # install.packages("purrr") library(purrr) # Collect all function outputs report_results <- map(seq_len(nrow(df2)), ~do_reports(df1, df2[., ], df3)) # Extract and row-bind the first report type combined_report1 <- map_dfr(report_results, ~.[[1]]) # Extract and row-bind the second report type combined_report2 <- map_dfr(report_results, ~.[[2]])
Bonus: Add a Row Identifier (Optional)
If you want to track which row of df2 each result came from, you can add an extra column to each output before combining:
# Using base R report_results <- lapply(seq_len(nrow(df2)), function(row_idx) { res <- do_reports(df1, df2[row_idx, ], df3) # Add a column to track the df2 row number res[[1]]$df2_source_row <- row_idx res[[2]]$df2_source_row <- row_idx res }) # Then combine as before combined_report1 <- do.call(rbind, lapply(report_results, function(x) x[[1]]))
This way, you can easily trace back any entries in your final reports to the specific row of df2 that generated them.
内容的提问来源于stack exchange,提问作者Lila McPhee

