Brian Smith
Brian Smith

Reputation: 1353

Apply custom function that returns multiple values after dplyr::rowwise()

I attempted to apply a custom function on each row using dplyr::rowwose() as below

library(dplyr)
dat = data.frame('A' = 1:3, 'C' = 1:3, 'D' = 1:3, 'M' = 1:3)
dat %>%
    rowwise() %>%
    mutate(c('A1', 'A2') = function(x) {c('A' + 5, 'D')})

So basically here, my custom function takes columns A and D and then perform some calculation and return a vector, which I want to append to the original data frame.

However above implementation is failing.

Can you please help with some insight how can I use rowwise() function to perform above calculation? Above example of applied function is fairly simple, however in my original case, such function is pretty complex. Also, I do not prefer to define that function stand alone basis, rather want to define on-the-fly within mutate to keep my code tidy.

Any pointer will be very helpful.

Upvotes: 2

Views: 453

Answers (1)

akrun
akrun

Reputation: 887108

If we need to create a function that returns a vector or list or a tibble

library(dplyr)
library(tidyr)
f1 <- function(x, y) tibble(A1 = x + 5, A2 = y + 1)
dat %>% 
   mutate(Anew = f1(A, D)) %>%
   unnest_wider(Anew)
# A tibble: 3 × 6
      A     C     D     M    A1    A2
  <int> <int> <int> <int> <dbl> <dbl>
1     1     1     1     1     6     2
2     2     2     2     2     7     3
3     3     3     3     3     8     4

Upvotes: 5

Related Questions