How can I create a loop to create a new variable for different dataframes

Solution 1:

It may be better to load the datasets into a list and then perform the operation at once and store the output in a list instead of creating more objects in the global env

library(purrr)
library(dplyr)
lst1 <- mget(ls(pattern = "^m.*\\d+_\\d+$")) %>%
    map(~ .x %>%
            mutate(hhid = xa * 10^5 + hoso))

If we need to update the original object, use list2envon the output list

list2env(lst1, .GlobalEnv)