Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Mutate All columns in a list of tibbles

Lets suppose I have the following list of tibbles:

a_list_of_tibbles <- list(
  a = tibble(a = rnorm(10)),
  b = tibble(a = runif(10)), 
  c = tibble(a = letters[1:10])
)

Now I want to map them all into a single dataframe/tibble, which is not possible due to the differing column types.

How would I go about this?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I have tried this, but I want to get rid of the for loop

for(i in 1:length(a_list_of_tibbles)){
  a_list_of_tibbles[[i]] <- a_list_of_tibbles[[i]] %>% mutate_all(as.character)
}

Then I run:

map_dfr(.x = a_list_of_tibbles, .f = as_tibble)

>Solution :

We could do the computation within the map – use across instead of the suffix _all (which is getting deprecated) to loop over the columns of the dataset

library(dplyr)
library(purrr)
map_dfr(a_list_of_tibbles, 
     ~.x %>%
       mutate(across(everything(), as.character) %>%
       as_tibble))

-output

# A tibble: 30 × 1
   a                 
   <chr>             
 1 0.735200825884485 
 2 1.4741501589461   
 3 1.39870958697574  
 4 -0.36046362308853 
 5 -0.893860999301402
 6 -0.565468636033674
 7 -0.075270267983768
 8 2.33534260196058  
 9 0.69667906338348  
10 1.54213170143702  
# … with 20 more rows
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading