Merge data frames: Add new levels to factor and match values to newly added factors

May be we can group_split by ‘div_var’, loop over the list of datasets, bind with ‘df2’, and then do a group by ‘year’, ‘elev_cat’ and fill the columns ‘div_var’, ‘div_value’ NAs with the previous non-NA value

library(dplyr)
library(purrr)
library(tidyr)
df1 %>%
    group_split(div_var) %>%
    map_dfr(~ bind_rows(., df2)  %>% 
    group_by(year, elev_cat) %>% 
    fill(div_var, div_value)) %>%
    ungroup

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top