Mutating for each element of a list

Let's say I have 1 list containing multiple data frames (2 for this example), and I have a vector with the same # of elements as there are data frames, and I want to mutate that vector to each data frame (element 1 for data frame 1 and element 2 for data frame 2). Any idea how I'd do that?

I'm about 99% sure I've done this before with purrr::map and dplyr::mutate but I can't remember how.

Here's some reproducible data that may help explain what I mean. The idea is that I want every row of mtcars to have a column that says mtcars and every row of iris to have a column that says iris.

df_list <- list(mtcars = as_tibble(mtcars), iris = as_tibble(iris))

df_names <- c("mtcars", "iris")

Alright, so not only have I done this before, but when I searched harder on Stack Overflow, I realized that I even upvoted a few answers that were really helpful.

This works:

df_list %>%
  map2(df_names, ~mutate(.x, name = .y))
3 Likes

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.