如何基于查找表多次执行R函数以修正时间戳
Solution to Iterate Over Break Records
First, ensure your break records are sorted by their occurrence date—this is critical to apply adjustments in the correct chronological order:
# Sort df2 by break date df2_sorted <- df2[order(df2$date), ]
Method 1: For Loop (Straightforward)
Use a loop to sequentially apply your break_function to each row of the sorted break records, updating the dataframe incrementally:
# Initialize with original df1 updated_df1 <- df1 # Iterate over each row in sorted df2 for (row_idx in seq_len(nrow(df2_sorted))) { updated_df1 <- break_function(updated_df1, df2_sorted, row_idx) }
Method 2: Functional Approach with Reduce
For a more concise, functional-style solution, use Reduce to cumulatively apply the function across all break records:
# Apply break_function cumulatively using Reduce updated_df1 <- Reduce( function(current_df, row_idx) break_function(current_df, df2_sorted, row_idx), seq_len(nrow(df2_sorted)), init = df1 )
Verification
To confirm the adjustments work, compare original and updated timestamps. For example:
# Original timestamp sample head(df1) # Updated timestamp sample head(updated_df1)
Both methods will correctly add the sum of all applicable break durations to each timestamp that occurs after the corresponding break times.
内容的提问来源于stack exchange,提问作者Baddevs
相关产品推荐
相关产品推荐

