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:
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
CodePudding user response:
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