multivariable function in long-format dataframe in R

Viewed 45

Calculating a function of multiple variables for a dataframe in wide format is very familiar:

library(tidyverse)
df <- tibble(t = 1:3, b = 11:13, c = 21:23) 
df <- df %>% mutate(d = b + c) # or base R: df$d <- df$b + df$c

What about when the dataframe is in long format? e.g.

df <- df %>% pivot_longer(-t, names_to = "variable", values_to = "value")

In this long format, you could imagine the same operation working by first group_by(t), and then calculating one value of d for each group, namely that group's variable=b value plus that group's variable=c value. Is this possible? One might think of something like summarise(d = b + c) but that expects wide format.
NB my real-world example has more than two cols b and c and I want to put them into a defined function, not just add them. My working solution is pivoting a huge dataframe from long to wide, calling my multivariable function to define a new column, then pivoting back to long.
Edit: to make the real world example explicit, I need to call a defined function that treats its arguments differently, unlike sum. For example

my.func <- function(b, c) { b^c }

How could the variable d be calculated by applying this function to the values of b and c associated with the same value of t?

1 Answers

We can just do sum instead of +

library(dplyr)
library(tidyr)
df %>% 
    group_by(t) %>% 
    summarise(d =sum(value[variable %in% c('b', 'c')]))

If it is to apply the my.func, we need to extract the value that correspond to 'b', 'c'

df %>% 
    group_by(t)  %>%
    mutate(new = my.func(value[variable == 'b'], value[variable == 'c']))
Related