1

I would like to know how to create a loop to create the same new variable for 7 different dataframes. Currently, my code looks like this:

m1_02 <- m1_02 %>% mutate(hhid = xa*10^5 + hoso)
m2_02 <- m2_02 %>% mutate(hhid = xa*10^5 + hoso)
m3_02 <- m3_02 %>% mutate(hhid = xa*10^5 + hoso)
m3_02a <- m3_02a %>% mutate(hhid = xa*10^5 + hoso)
m6a2_02 <- m6a2_02 %>% mutate(hhid = xa*10^5 + hoso)
m6b1_02 <- m6b1_02 %>% mutate(hhid = xa*10^5 + hoso)
m6b2_02 <- m6b2_02 %>% mutate(hhid = xa*10^5 + hoso)

I was wondering if there was a way I could create a loop that would create the hhid variable in the respective dataframes without having to use the mutate function one by one.

Thank you!

anrisakaki96
  • 193
  • 8
  • 1
    Since you're doing the same thing to multiple frames, it's likely better to work with a [list of frames](https://stackoverflow.com/a/24376207/3358227) instead of keeping them as separate objects. – r2evans Jan 19 '22 at 17:04

1 Answers1

2

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)
akrun
  • 874,273
  • 37
  • 540
  • 662