79803214

Date: 2025-10-28 19:51:33
Score: 0.5
Natty:
Report link

Solved this with a custom function. There probably exists a more performant solution but this has worked for my needs.


row_updater <- function(df1, df2, id){

  df_result_tmp <- df1 %>%
    # append dfs and create column denoting input df 
    dplyr::bind_rows(df2, .id="df_id") %>%
    # count number of rows per id
    dplyr::group_by({{id}}) %>%
    dplyr::mutate(id_count = n()) %>%
    dplyr::ungroup()
  
  if (max(df_result_tmp['id_count']) > 2){
    warning(paste0("Attempted to update more than 1 row per ", quote(id), ". Check input datasets for duplicated rows."))
  }
  df_result <- df_result_tmp %>%
    # filter to unaltered rows from df1 and rows from df2
    dplyr::filter(id_count == 1 | (id_count == 2 & df_id == 2)) %>%
    dplyr::select(-c(df_id, id_count))
  
  return(df_result)
}
Reasons:
  • Long answer (-0.5):
  • Has code block (-0.5):
  • Self-answer (0.5):
  • Low reputation (1):
Posted by: sbj