The difference between Map() and map () from Purrr package in R

Viewed 516

hi I was trying to add a name column into all of the elements in my list using the names of the list. That is I have 8 tables in my list, each table has its own name table 1...8. So later I can unlist them and differentiate where the table comes from.

I have read this post and the code works. R - Add columns to dataframes in list by looping through elements in a vector

my_list <- Map(cbind, mylist, Cluster = names(mylist))

However, I don't quite understand the Map(). This is not the map() from Purrr package right? map() will take the arguments in order map(data, function). I checked in Rstudio help on Map, it looks more confusing. And if I'm to use the Purrr map function, I tried this

my_list2 <- map(mylist, function(x)cbind(x,Cluster = names(x)))

it did not work. could someone enlighten me how Map works and if I'm going to use map(), what are the changes I should do?

2 Answers

They are indeed different functions. If your list is already named you can certainly use purrr::map to add a named column. Please see this recent question since you didn't provide any specifics.

Best guess at what you want is:

purrr::map2(mylist, names(mylist), ~ mutate(.x, new_column_name = .y))

Maybe this is what you are looking for. To add a column with the name of the list you have to loop both over the list and the names. This could be easily achieved via purrr::imap which is a wrapper for purrr::map2 or you can use base Map. The main difference is probably that in Map the function to apply is the first argument. Additonally the purrr family of map functions allows for using formula notation (see the example in my code) for writing anonymous functions

mylist <- list(
  a = data.frame(x = 1 , y = 2),
  b = data.frame(x = 3, y = 4)
)

purrr::imap(mylist, ~ cbind(.x, Cluster = .y))
#> $a
#>   x y Cluster
#> 1 1 2       a
#> 
#> $b
#>   x y Cluster
#> 1 3 4       b

Map(function(x, y) { cbind(x, Cluster = y) }, mylist, names(mylist))
#> $a
#>   x y Cluster
#> 1 1 2       a
#> 
#> $b
#>   x y Cluster
#> 1 3 4       b
Related