Skip to content

Instantly share code, notes, and snippets.

@jimjam-slam
Last active July 27, 2023 01:06
Show Gist options
  • Save jimjam-slam/d0872e6daed721e007367875bed074a6 to your computer and use it in GitHub Desktop.
Save jimjam-slam/d0872e6daed721e007367875bed074a6 to your computer and use it in GitHub Desktop.
pmapping by position #experiments
my_func <- function(alpha, beta, gamma) alpha + beta + gamma
# no
tibble(a = 1:5, b = 6:10, c = 11:15) %>%
mutate(z = pmap_int(., my_func))
# yes
tibble(a = 1:5, b = 6:10, c = 11:15) %>%
mutate(z = pmap_int(
dplyr::select(., alpha = a, beta = b, gamma = c),
my_func))
# no
list(a = 1:5, b = 6:10, c = 11:15) |>
pmap_int(my_func)
# no
list(a = 1:5, b = 6:10, c = 11:15) |>
pmap_int(function(alpha, beta, gamma) alpha + beta + gamma)
# yes
list(x, y, z) |>
pmap_int(function(first, second, third) (first + third) * second)
# no
list(
a = list(1, 2, 3, 4, 5),
b = list(6, 7, 8, 9, 10),
c = list(11, 12, 13, 14, 15)) |>
pmap_int(function(first, second, third) (first + third) * second)
# yes! works as long as "columns" are unnamed
list(
list(1, 2, 3, 4, 5),
list(6, 7, 8, 9, 10),
list(11, 12, 13, 14, 15)) |>
pmap_int(function(first, second, third) (first + third) * second)
# no: can't use mutate on a list, only on a df
tibble(a = 1:5, b = 6:10, c = 11:15) |>
`class<-`("list") |>
set_names(NULL) |>
mutate(.data = _, z = pmap_int(.l = _, my_func))
by_pos <- function(df) {
df |> `class<-`("list") |> set_names(NULL)
}
# yes!
tibble(a = 1:5, b = 6:10, c = 11:15) %>%
mutate(z = pmap_int(by_pos(.), my_func))
# yes! (but clunky)
tibble(a = 1:5, b = 6:10, c = 11:15) |>
(\(df) mutate(df, z = pmap_int(by_pos(df), my_func)))()
# yes! (also clunky)
tibble(a = 1:5, b = 6:10, c = 11:15) |>
(\(df) mutate(df, z = pmap_int(
by_pos(df),
function(alpha, beta, gamma) alpha + beta + gamma)))()
# deliberately returning a list to test list-cols
my_func2 <- function(alpha, beta, gamma) {
list(paste(as.character(alpha), as.character(beta), as.character(gamma), sep = "-"))
}
# uh, yeah, this is heaps better
tibble(a = 1:5, b = 6:10, c = 11:15) |>
rowwise() |>
mutate(z = my_func2(a, b, c))
# jenny's solution
# yes!
tibble(a = 1:5, b = 6:10, c = 11:15) %>%
mutate(z = pmap_int(
list(alpha = a, beta = b, gamma = c),
my_func))
# YES!
tibble(a = 1:5, b = 6:10, c = 11:15) |>
mutate(z = pmap_int(
list(alpha = a, beta = b, gamma = c),
my_func))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment