Last active
May 10, 2019 02:43
-
-
Save mfansler/0fca87b1afb9b7b784f73ca4a12cff90 to your computer and use it in GitHub Desktop.
Using tidyverse nesting to unpack a vector of results into a long-format tibble
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(tidyverse) | |
# values at which to evaluate | |
# this can be changed arbitrarily | |
x <- c(1,2,3) | |
# evaluate y's for every condition and output a long format table | |
df <- expand.grid(coef=c(1,2), pow=c(1,2,3)) %>% | |
group_by(coef, pow) %>% | |
mutate(y=map2(coef, pow, ~ tibble(x=x, y=.x*x^.y))) %>% | |
unnest() | |
df | |
## A tibble: 18 x 4 | |
## Groups: coef, pow [6] | |
# coef pow x y | |
# <dbl> <dbl> <dbl> <dbl> | |
# 1 1 1 1 1 | |
# 2 1 1 2 2 | |
# 3 1 1 3 3 | |
# 4 2 1 1 2 | |
# 5 2 1 2 4 | |
# 6 2 1 3 6 | |
# 7 1 2 1 1 | |
# 8 1 2 2 4 | |
# 9 1 2 3 9 | |
#10 2 2 1 2 | |
#11 2 2 2 8 | |
#12 2 2 3 18 | |
#13 1 3 1 1 | |
#14 1 3 2 8 | |
#15 1 3 3 27 | |
#16 2 3 1 2 | |
#17 2 3 2 16 | |
#18 2 3 3 54 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment