Home > Enterprise >  R: How to apply a similar mutate() to multiple data frames with purrr without creating a list?
R: How to apply a similar mutate() to multiple data frames with purrr without creating a list?

Time:08-16

I have seen similar posts, but none that address this question specifically. So, I have three data frames that are similar, and I'm applying a similar mutate() to each of them.

xk <- xk %>% 
    mutate(country="Kosovo",
           date=ym(date)) %>% 
    relocate(country)

al <- al %>% 
    mutate(country="Albania",
           date=ym(date)) %>% 
    relocate(country)

mne <- mne %>% 
    mutate(country="Montenegro",
           date=my(date)) %>% 
    relocate(country)

Can I use one of the functions contained in the purrr package to do that with as few lines of code as possible?

CodePudding user response:

there is a way that will work with or without purrr.

  1. convert your data.frames to data.tables
  2. use mapply (or the purrr's equivalent) to do the same operation on all tables
  3. you don't care about the output of mapply, because data.tables will be changed without assignment to a new variable
library(data.table)
xk <- as.data.table(xk)
al <- as.data.table(al)
mne <- as.data.table(mne)

mapply(function(x,y) x[,country:=y], x=list(xk,al,mne), y=c("Kosovo","Albania","Montenegro"))

print(xk)
  • Related