Home > OS >  How can I mutate and create a new variable using for loops
How can I mutate and create a new variable using for loops

Time:03-07

I have the current code to create a new variable called hhid in each dataframe within the list hh02.

hh02 <- list(exp_02, m1_02, m2_02, m3_02, m6a2_02, m6b1_02, m6b2_02, m6b34_02)

for(i in 1:length(hh02)){
 hh02[[i]] = hh02[[i]] %>%
   mutate(hhid = xa*10^5   hoso)
}

However, when I run this code, I cannot see the new hhid variable in the dataframes. What am I doing wrong?

Thank you

CodePudding user response:

Try this:

lapply(hh02, \(x) mutate(x, hhid = xa*10^5   hoso))

Note that you will see that this returns a list of frames, with the new column added, but it won't change hh02, or the frames initially placed in hh02

If you want to change the initial frames, you could do something like this

hh02 <- c("exp_02","m1_02")
for( h in hh02) {
  assign(h, mutate(get(h), hhid = xa*10^5   hoso))
}
  • Related