在曲棍球数据框df每行后插入条件化行的实现方法
解决方案:为每行插入指定规则的新行
我来帮你实现这个需求,结合你提到的purrr思路,我们可以用两种不同的tidyverse方法来完成,下面是具体实现:
方法1:使用dplyr的rowwise + unnest(更直观)
这种方法逐行处理原数据,生成对应的新行后展开,代码可读性更强:
library(tidyverse) # 第一步:给原数据添加临时行标识,确保原行和新行对应 df_with_row_id <- df %>% mutate(temp_row_id = row_number()) # 第二步:逐行生成新行并合并 final_df <- df_with_row_id %>% rowwise() %>% # 生成符合规则的新行 mutate(inserted_row = list(tibble( event_index = NA, # 新行的event_index设为NA,若需要自定义值可调整 coords_x = case_when( event_rinkside == "R" ~ 82, event_rinkside == "L" ~ -82, TRUE ~ NA_real_ # 处理event_rinkside为NA的情况 ), coords_y = case_when( event_rinkside %in% c("R", "L") ~ 0, TRUE ~ NA_real_ ), event_rinkside = event_rinkside, temp_row_id = temp_row_id ))) %>% # 把每个原行和新行展开成两行 unnest(inserted_row) %>% # 移除临时行标识,调整顺序确保原行在前、新行在后 select(-temp_row_id) %>% arrange(floor(row_number() / 2) %>% rep(each = 2))
方法2:使用purrr的map_dfr(贴合你提到的Stack Overflow思路)
这种方法和你参考的方案结构类似,通过拆分数据后遍历处理:
library(purrr) library(dplyr) final_df <- df %>% mutate(temp_row_id = row_number()) %>% # 按临时行标识拆分成单个行的列表 split(.$temp_row_id) %>% # 遍历每个行元素,生成新行并合并 map_dfr(function(single_row) { inserted_row <- tibble( event_index = NA, coords_x = ifelse(single_row$event_rinkside == "R", 82, ifelse(single_row$event_rinkside == "L", -82, NA)), coords_y = ifelse(single_row$event_rinkside %in% c("R", "L"), 0, NA), event_rinkside = single_row$event_rinkside ) # 合并原行和新行 bind_rows(single_row, inserted_row) }) %>% select(-temp_row_id)
关键细节说明
- NA值处理:原数据中第35行的
event_rinkside为NA,两种方法都会将对应新行的coords_x和coords_y设为NA,符合逻辑; - event_index字段:新行的
event_index我设为NA,如果需要自定义(比如原event_index加0.5),直接修改代码中对应的值即可; - 行顺序:两种方法都确保原行在前,新插入的行在后,最终总行数为114行,完全符合需求。
内容的提问来源于stack exchange,提问作者user8248672
相关产品推荐
相关产品推荐

