1

I want to take a data frame from my list and add to it another column with the name variable, same as lists name. and I want to achieve that using purrr. any other solutions are also welcome!

dat_list <- list(a = as_tibble(rnorm(5)), b= as_tibble(rnorm(5)))

dat_list
$a
# A tibble: 5 x 1
       value
       <dbl>
1 -1.0946024
2  0.1010983
3 -0.1817757
4  0.5394615
5 -1.4450060

$b
# A tibble: 5 x 1
        value
        <dbl>
1 -0.58095984
2  0.50843100
3 -0.01598389
4  0.05894331
5  0.36958224


map2(.x = dat_list,.y = names(dat_list) ,.f = function(x){.y %>% mutate(var <- .x)})
Shoaibkhanz
  • 1,942
  • 3
  • 24
  • 41
  • Maybe this `Map(cbind, dat_list, variable = names(dat_list))`? – Sotos Dec 14 '17 at 10:11
  • Both solutions work and I think it solves the problem. But I wonder how can we implement the same using map2 in purrr! – Shoaibkhanz Dec 14 '17 at 10:14
  • 2
    `purrr` translation is easy...`map2(dat_list, names(dat_list), ~ mutate(.x, var = .y))` – Sotos Dec 14 '17 at 10:19
  • 1
    Brilliant that worked perfectly! thanks Sotos – Shoaibkhanz Dec 14 '17 at 10:27
  • FYI, starting in *purrr_0.2.3* there is a "short-hand" family of `imap` indexed functions when you want to loop through a list and the names (or indexes) of the list simultaneously. – aosmith Dec 14 '17 at 18:14

0 Answers0