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

R Convert datatype of a list of tibbles

Similar to this question, I would like to do the same but to a list of tibbles.

How can I do this?

Sample Data & code:

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

library(tidyverse)

tbl1 = tibble(x = c('a', 'b', 'c'), y = 1:3)
tbl2 = tibble(x = c('11', '12', '13'), y = 1:3)

tbl = list(tbl1, tbl2)

data_types = rep(c("character"),times = 3)

tbl[] = map2(tbl, str_c("as.", data_types), ~ get(.y)(.x))

Error:

Error: Mapped vectors must have consistent lengths:
* `.x` has length 2
* `.y` has length 3

>Solution :

In the linked post, it is having different column types, so we created a vector of types with length equal to the number of columns in the data. Here, the number of columns in each of the datasets in the list is 2. Thus, the rep with times should be 2

data_types <- rep(c("character"),times = 2)

Also, as we have to loop over the list, do a nested map/map2

library(purrr)
map(tbl, ~ map2_dfr(.x, str_c("as.", data_types), ~ get(.y)(.x)))

Or as there is a single type, we can also do

map(tbl,  ~map_dfr(.x, as.character)) 

-output

[[1]]
# A tibble: 3 × 2
  x     y    
  <chr> <chr>
1 a     1    
2 b     2    
3 c     3    

[[2]]
# A tibble: 3 × 2
  x     y    
  <chr> <chr>
1 11    1    
2 12    2    
3 13    3    
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