I have a data frame. For argument's sake, let's say it's the datasets::women
data frame. I want to create a vector from the frame by applying a function to each row.
It seems that the usual way to do this is to use dplyr
and call mutate
or transmute
, for example:
dplyr::transmute(women, some_index = 2 * height + weight)
Great: that works.
But what if I pull out the calculation of some_index
into a function which acts on a row:
calc_some_index <- function(woman) {
2 * woman$height + woman$weight
}
Is there a way I should call mutate
/transmute
so that it calls this function on each row of its input?
Of course, I can see that I get the right result if I call
dplyr::transmute(women, some_index=calc_some_index(women))
but I believe this is just 'cheating' by subbing the calculated vector in, pre-calculated, to the transmute
call. It doesn't work, for instance, if I call:
dplyr::transmute(head(women, n=10), some_index=calc_some_index(women))