Home > Software design >  How to mutate the same variables across two or more dataframes?
How to mutate the same variables across two or more dataframes?

Time:11-08

I am looking to mutate the same variables with two or more dataframes. What is the best way to implement to reduce redundant code?

library(dplyr)
df1 <- tibble(a = 0.125068, b = 0.144623)
df2 <- tibble(a = 0.226018, b = 0.423600)

df1 <- df1 %>% 
  mutate(a = round(a, 1),
         b = round(b, 2))
df2 <- df2 %>% 
  mutate(a = round(a, 1),
         b = round(b, 2))

CodePudding user response:

You could make a function

rnd <- function(x) {
  x %>% 
  mutate(a = round(a, 1),
         b = round(b, 2))
}

df1 %>% rnd()

CodePudding user response:

It may be interesting to put the dataframes in a list first:

my_dfs <- list(df1, df2)

Then use a loop-apply function like lapply:

lapply(my_dfs, \(x) mutate(x, a = round(a, 1),
                              b = round(b, 2))

If we really need the dataframes in the global environment, instead of in a dedicated list, we can simply call list2env(), as in:

lapply(my_dfs, \(x) mutate(x, a = round(a, 1),
                              b = round(b, 2)) |>
       list2env(envir = .GlobalEnv))
  •  Tags:  
  • r
  • Related