Add a new variable to the list of data frames using purrr and mutate () from dplyr

I know that there are many related questions here, but I'm looking for a solution to purrr, please, not one of the list of applications or cbind / rbdind (I want to take this opportunity to get to know purrr better).

I have a list of data frames, and I would like to add a new column to each data file in the list. The value of the column will be the name of the data frame, that is, the name of each item in the list.

There is something similar here, but it is related to using the function and mutate_each(), whereas I need it simply mutate().

To give you an idea of ​​the list (called comentarios), here is the first line str()for the first item:

> str(comentarios[1])
List of 1
 $ 166860353356903_661400323902901:'data.frame':    13 obs. of  7 variables:

Therefore, I want my new variable to contain 166860353356903_66140032390290113 lines for the result, as an identifier for each data frame.

I'm trying to:

dff <- map_df(comentarios, 
              ~ mutate(ID = names(comentarios)),
              .id = "Group"
              )

However, a mutate()data frame name is required for operation :

Error in mutate_(.data, .dots = lazyeval::lazy_dots(...)) : 
  argument ".data" is missing, with no default

It makes no sense to insert each name, I would deviate to the territory of the cycle and lose the advantages of purrr (and R, more generally). If the list was smaller, I would use reshape::merge_all(), but it has more than 2000 elements. Thank you in advance for any help.

edit: some data to make the problem reproducible, according to alistaire comments

# install.packages("tidyverse")
library(tidyverse)
df <- data_frame(one = rep("hey", 10), two = seq(1:10), etc = "etc")

list_df <- list(df, df, df, df, df)
names(list_df) <- c("first", "second", "third", "fourth", "fifth")
dfs <- map_df(list_df, 
              ~ mutate(id = names(list_df)),
              .id = "Group"
              )
+4
source share
2 answers

, , mutate with piping. map2_df

dff <- map2_df(comentarios, names(comentarios), ~ mutate(.x, ID = .y)) 
+8

OP

library(tidyverse)
df <- data_frame(one = rep("hey", 10), two = seq(1:10), etc = "etc")

list_df <- list(df, df, df, df, df)
dfnames <- c("first", "second", "third", "fourth", "fifth")

dfs <- list_df %>% map2_df(dfnames,~mutate(.x,name=.y))
0

Source: https://habr.com/ru/post/1668760/


All Articles