Why is R dplyr::mutate inconsistent with custom functions

前端 未结 2 1509
时光说笑
时光说笑 2020-12-16 23:32

This question is a \"why\", not a how. In the following code I\'m trying to understand why dplyr::mutate evaluates one custom function (f()) with t

相关标签:
2条回答
  • 2020-12-17 00:25

    sin and ^ are vectorized, so they natively operate on each individual value, rather than on the whole vector of values. f is not vectorized. But you can do f = Vectorize(f) and it will operate on each individual value as well.

    y1 <- mutate(df, asq=a^2, fout=f(a), gout=g(a))
    y1
    
        a   asq     fout       gout
    1   0     0 3640.889  0.0000000
    2  10   100 3640.889 -0.5440211
    3 100 10000 3640.889 -0.5063656
    
    f = Vectorize(f)
    
    y1a <- mutate(df, asq=a^2, fout=f(a), gout=g(a))
    y1a
    
        a   asq        fout       gout
    1   0     0    10.88874  0.0000000
    2  10   100  1010.88874 -0.5440211
    3 100 10000 10010.88874 -0.5063656
    

    Some additional info on vectorization here, here, and here.

    0 讨论(0)
  • 2020-12-17 00:39

    We can loop through each element of 'a' using map and apply the function f

    library(tidyverse)
    df %>%
        mutate(asq = a^2, fout = map_dbl(a, f), gout = g(a)) 
    #    a   asq        fout       gout
    #1   0     0    10.88874  0.0000000
    #2  10   100  1010.88874 -0.5440211
    #3 100 10000 10010.88874 -0.5063656
    
    0 讨论(0)
提交回复
热议问题