Home > Software design >  tidyverse, purrr, not able to keep labels
tidyverse, purrr, not able to keep labels

Time:05-01

I'm teaching myself tidyverse, and working on purrr at the moment. For example, using map_dbl() to find the variance of the features of a data set is clear. This returns a list. For example:

library(tidyverse)
diamonds %>%
  select_if(is.numeric) %>% 
  map_dbl(var)

The result looks like:

enter image description here

So far so good. But if I want to do anything (such as sort the results), the labels are lost. For example:

  select_if(is.numeric) %>% 
  map_dbl(var) %>% 
  as_tibble() %>% 
  arrange(value)

This loses the labels. For example:

enter image description here

How is this done in the tidyverse a way that keeps the labels?

CodePudding user response:

You can do this which keeps it as a tibble throughout.

It's worth reading about tidy data, where each variable must have its own column and each observation must have its own row.

library(tidyverse)

diamonds %>%
  summarise(across(where(is.numeric), var)) %>%
  pivot_longer(everything()) %>% 
  arrange(value)
#> # A tibble: 7 × 2
#>   name         value
#>   <chr>        <dbl>
#> 1 carat        0.225
#> 2 z            0.498
#> 3 x            1.26 
#> 4 y            1.30 
#> 5 depth        2.05 
#> 6 table        4.99 
#> 7 price 15915629.

Created on 2022-04-30 by the reprex package (v2.0.1)

  • Related