0

Say I have these data and this function:

a <- data.frame(a= c(1,2,3), b=c(2,3,4))

fun <- function(q,y,z) {
    r <- data.frame(a = c(q+y, q, q, y), b= c(q,q,q,z))
    r
}

I would like to apply the function to each row individually and create a list column, where each row has its own data frame in this new column.

Here is what I tried, but it gives an error.

b <- a %>% rowwise(a) %>% mutate(list1 = list(fun(a, b, c)))
bill999
  • 2,147
  • 8
  • 51
  • 103

1 Answers1

1

There is no c column in the data. If we want to pass a default value for 'z'

library(dplyr)
out <- a %>% 
    rowwise %>%
    mutate(list1 = list(fun(a, b, z = 0)))

-output

out$list1
[[1]]
  a b
1 3 1
2 1 1
3 1 1
4 2 0

[[2]]
  a b
1 5 2
2 2 2
3 2 2
4 3 0

[[3]]
  a b
1 7 3
2 3 3
3 3 3
4 4 0
akrun
  • 874,273
  • 37
  • 540
  • 662