using spread() within map()

Viewed 176

I'm struggling using spread() within a map() function. Here is an example data:

data1 <- tibble(size = c("1", "2", "3", "4"),
               color = c("blue", "green", "yellow", "black"))

data2 <- tibble(size = c("7", "3", "10", "1"),
                color = c("orange", "yellow", "red", "white"))

dataList <- list(data1, data2)

What I want to achieve with my list is similar to that with a single tibble:

spread(data1, size, color)

# A tibble: 1 x 4
  `1`   `2`   `3`    `4`  
  <chr> <chr> <chr>  <chr>
1 blue  green yellow black

But I want to somehow apply this spread() over the two tibbles of my list, using map(). But I can't find the right way to do that... Any idea? Thanks a lot for your help!

1 Answers

Using tidyr::pivot_wider since tidyr::spread is depreciated :

data1 <- tibble::tibble(size = c("1", "2", "3", "4"),
        color = c("blue", "green", "yellow", "black"))

data2 <- tibble::tibble(size = c("7", "3", "10", "1"),
        color = c("orange", "yellow", "red", "white"))

dataList <- list(data1, data2)

purrr::map(.x = dataList, .f = ~tidyr::pivot_wider(.x, names_from = size, values_from = color) )
#> [[1]]
#> # A tibble: 1 x 4
#>   `1`   `2`   `3`    `4`  
#>   <chr> <chr> <chr>  <chr>
#> 1 blue  green yellow black
#> 
#> [[2]]
#> # A tibble: 1 x 4
#>   `7`    `3`    `10`  `1`  
#>   <chr>  <chr>  <chr> <chr>
#> 1 orange yellow red   white
Related