elliot
elliot

Reputation: 1944

Add new single-character variables to list of dataframes in R

I need to merge a long list of dataframes in R, and I'd like to create an identifier variable for each using purrr::map and dplyr::mutate. The result will be a new variable for each dataframe that is unique and a single string.

Here is a reprex of the error I'm getting. How can I fix this?

library(tidyverse)

df_1 <- mtcars %>% 
    as_tibble() %>% 
    select(1:3)

df_2 <- mtcars %>% 
    as_tibble() %>% 
    select(4:6)

df_ls <- list(df_1, df_2)


new_vary <- c('first dataframe', 'second dataframe')


map2(df_ls, new_vary, function(x, y){
    x %>% 
        mutate(new_variable = new_vary)
})
#> Error: Column `new_variable` must be length 32 (the number of rows) or one, not 2

Upvotes: 1

Views: 36

Answers (1)

akrun
akrun

Reputation: 886948

We can use the y if it is anonymous function or .y with ~

map2(df_ls, new_vary, ~ .x %>% 
                               mutate(new_variable = .y))

In base R, it is done with Map

Map(cbind, df_ls, new_variable = new_vary)

NOTE: 'new_vary' is a vector with two elements. With map2, it is looping through teach element of the list ('df_ls') along with the corresponding element of 'new_vary'. Calling the 'new_vary' inside the mutate will get the whole vector instead of the element inside the vector

Upvotes: 3

Related Questions