rdplyr

How to return multiple columns from one function inside `mutate` and allow me to name the output columns?


Consider this code:

library(dplyr)
a = data.frame(a = 1:3)
abc = \(x) data.frame(x/2, x/3)
a %>% 
  mutate(abc(a))

which returns

  a x.2       x.3
1 1 0.5 0.3333333
2 2 1.0 0.6666667
3 3 1.5 1.0000000

but I don't have control over the names as I want to assign them something else.

One way to solve this is to the return type of abc to be named but this is not ideal as I may want to run abc on two sets of variables

a %>% 
  mutate(abc(a), abc(b))

The other way is of course is to rename them after each run of abc but then that could be unstable.

Is there to way to give names to the output of abc? e.g.

a %>% 
  mutate(c("a1","a2") := abc(a), c("b1","b2") := abc(b))

But the above := syntax didn't work.


Solution

  • This feels weird to me; like you might be better off restructuring your data first, but without more context, I can't say for sure.

    df <- data.frame(a = 1:3, b = 4:6)
    abc <- \(x) data.frame(x/2, x/3)
    
    df %>%
      mutate(
        abc(a) %>% setNames(c("a1", "a2")),
        abc(b) %>% setNames(c("b1", "b2"))
      )
    
    ##   a b  a1        a2  b1       b2
    ## 1 1 4 0.5 0.3333333 2.0 1.333333
    ## 2 2 5 1.0 0.6666667 2.5 1.666667
    ## 3 3 6 1.5 1.0000000 3.0 2.000000