Created
March 24, 2023 20:13
-
-
Save TimTeaFan/6571d1bf87f9b3eddf1d8d7cade5964c to your computer and use it in GitHub Desktop.
using `table()` in list-column of nested data
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) | |
mtcars %>% | |
nest_by(gear) %>% | |
mutate(freq = rlang::list2( | |
"gear_{gear}_carb" := table(data$carb) | |
)) %>% | |
pull(freq) | |
#> $gear_3_carb | |
#> | |
#> 1 2 3 4 | |
#> 3 4 3 5 | |
#> | |
#> $gear_4_carb | |
#> | |
#> 1 2 4 | |
#> 4 4 4 | |
#> | |
#> $gear_5_carb | |
#> | |
#> 2 4 6 8 | |
#> 2 1 1 1 | |
mtcars %>% | |
nest_by(gear) %>% | |
mutate(freq = rlang::list2( | |
"gear_{gear}" := count(data, carb) | |
)) %>% | |
pull(freq) | |
#> $gear_3 | |
#> # A tibble: 4 × 2 | |
#> carb n | |
#> <dbl> <int> | |
#> 1 1 3 | |
#> 2 2 4 | |
#> 3 3 3 | |
#> 4 4 5 | |
#> | |
#> $gear_4 | |
#> # A tibble: 3 × 2 | |
#> carb n | |
#> <dbl> <int> | |
#> 1 1 4 | |
#> 2 2 4 | |
#> 3 4 4 | |
#> | |
#> $gear_5 | |
#> # A tibble: 4 × 2 | |
#> carb n | |
#> <dbl> <int> | |
#> 1 2 2 | |
#> 2 4 1 | |
#> 3 6 1 | |
#> 4 8 1 |
We can also rewrite the function to use unquoted
object names:
tablefun_unquoted <- function(data, xvar){
count(data, {{ xvar }})
}
mtcars %>%
nest_by(gear) %>%
mutate(freq = list(
tablefun_unquoted(data, carb)
)
) %>%
pull(freq)
#> same output as above
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This works too: