I have a large dataset that is grouped. For each row within the group, I need to extract a vector from one of the columns, and determine its minimum. The vector's length would be determined by the value in another column. I can do this with a combination of pmap_dbl() and group_map(), but I was wondering if there's a cleaner way of doing this while staying in the dplyr universe.
A toy example:
library(dplyr)
library(purrr)
dat <- data.frame(temp = rnorm(10, 10, 2),
start = c(1:5, 1:5),
end = c(2, 2, 4, 5, 5, 2, 3, 4, 5, 5),
group = c(rep("a", 5), rep("b", 5)))
Function to get the vectorized needed output, this returns the min value of the vector defined by start/end for each row:
fun.try <- function(dat, ...) {
pmap_dbl(list(start = dat$start, end = dat$end), function(x, start, end)
min(x$temp[start:end]), x = dat)
}
Applying the function by group:
dat %>%
group_by(group) %>%
group_map(.f = fun.try)
Is there a cleaner way of doing this, preferably using an anonymous function? Thank you!