Created
February 4, 2021 21:33
-
-
Save sharlagelfand/7245d2293b45399dec9a7f94dc1799ce to your computer and use it in GitHub Desktop.
please clean my data for me
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
library(dplyr) | |
library(tidyr) | |
initial <- tibble( | |
name = c("name_1", "name_2"), | |
value = list( | |
tibble(name = c("subname_1", "subname_2"), value = c(1, 2)), | |
tibble(name = c("subname_3", "subname_4"), value = c(3, 4)) | |
) | |
) | |
initial | |
#> # A tibble: 2 x 2 | |
#> name value | |
#> <chr> <list> | |
#> 1 name_1 <tibble [2 × 2]> | |
#> 2 name_2 <tibble [2 × 2]> | |
initial[1,][["value"]] | |
#> [[1]] | |
#> # A tibble: 2 x 2 | |
#> name value | |
#> <chr> <dbl> | |
#> 1 subname_1 1 | |
#> 2 subname_2 2 | |
desired <- tibble( | |
name_1 = tibble( | |
subname_1 = 1, | |
subname_2 = 2 | |
), | |
name_2 = tibble( | |
subname_3 = 3, | |
subname_4 = 4 | |
) | |
) | |
desired | |
#> # A tibble: 1 x 2 | |
#> name_1$subname_1 $subname_2 name_2$subname_3 $subname_4 | |
#> <dbl> <dbl> <dbl> <dbl> | |
#> 1 1 2 3 4 | |
initial_to_desired <- initial %>% | |
unnest_longer(value) %>% | |
pivot_wider(names_from = name, values_from = value, values_fn = list) %>% | |
mutate(across( | |
c(name_1, name_2), | |
function(x) { | |
pivot_wider(x[[1]], names_from = name, values_from = value) | |
} | |
)) | |
identical(initial_to_desired, desired) | |
#> [1] TRUE |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment