r - custom function with mutate do not work -
some custom functions not work in mutate. explain why calc2 , calc3 dont work, , how fix them work properly?
library(dplyr) m <- matrix(c(1,2,3,4,5,6,7,8,9), nrow = 3, byrow = t) calc <- function(x1,x2,x3){ #scalar return(x1 + x2 + x3) } calc2 <- function(x){ #vector return(x[1] + x[2] + x[3]) } calc3 <- function(x){ #list x <- unlist(x) return(sum(x)) } as.data.frame(m) %>% mutate(val = calc(v1,v2,v3), #ok val2 = calc2(c(v1,v2,v3) ), #ng val3 = calc3(list(v1,v2,v3))) #ng
below output:
v1 v2 v3 val val2 val3 1 2 3 6 12 45 4 5 6 15 12 45 7 8 9 24 12 45
we can without changing op's functions using rowwise
library(dplyr) as.data.frame(m) %>% rowwise() %>% mutate(val = calc(v1, v2, v3), val2 = calc2(c(v1, v2, v3)), val3 = calc3(list(v1, v2, v3))) # tibble: 3 × 6 # v1 v2 v3 val val2 val3 # <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> #1 1 2 3 6 6 6 #2 4 5 6 15 15 15 #3 7 8 9 24 24 24
Comments
Post a Comment