How to assign unique id to a list of dataframes AND apply other functions in one call

Viewed 63

I have code that assigns a unique.id to each data frame in my.list and left_joins them with new.df.

new.list = list(data.frame(x = c(1, 2), y = c("a", "b")), data.frame(x = c(1, 2), y = c("b", "b")))
new.df = data.frame(x = c(1, 2), y = c("a", "b"), z = c(1, 2))

new.list = Map(cbind, my.list, unique.id = (1:length(my.list)))

new.list = lapply(new.list, function(x) left_join(x, new.df))

How can you write this with one call preferably just using tidyverse?

1 Answers

You may use imap -

library(dplyr)
library(purrr)

imap(new.list, ~.x %>% 
                  mutate(unique.id = .y) %>%
       left_join(new.df))

#[[1]]
#  x y unique.id z
#1 1 a         1 1
#2 2 b         1 2

#[[2]]
#  x y unique.id  z
#1 1 b         2 NA
#2 2 b         2  2
Related