Home > OS >  Make custom function pipeable
Make custom function pipeable

Time:11-27

I'm trying to workout some code mixing pipe operators and a function.

The following line of code should compute the daily returns for some stocks that have been previously group by name.

mod_stock_data$daily_return = mod_stock_data %>% group_by(gvkey, iid)  %>% dailyReturn(prccd)

mod_stock_data is a dataframe that contains gvkey (stock's key name), iid (identfier), and prccd (closing value).

I'm using a pipe operator for the first step of grouping the dataframe by the stock's name. Once this operation is performed, the result of the group by is piped towards dailyReturn() function.

But instead of adding a new column with the daily returns, I get the following error:

Error in dailyReturn(., prccd) : unused argument (prccd)

Anyone can help?

The dailyReturn function:

dailyReturn <- function(tx) {
  returns  = tx / lag(tx, 1) - 1
  return(returns)
}

CodePudding user response:

If we modify the function, it can be used within mutate

dailyReturn <- function(tx) {
   tx / lag(tx, 1) - 1
  
 }

-testing

mtcars %>%
   group_by(cyl) %>% 
   mutate(out = dailyReturn(mpg))

-output

# A tibble: 32 × 12
# Groups:   cyl [3]
     mpg   cyl  disp    hp  drat    wt  qsec    vs    am  gear  carb     out
   <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>   <dbl>
 1  21       6  160    110  3.9   2.62  16.5     0     1     4     4 NA     
 2  21       6  160    110  3.9   2.88  17.0     0     1     4     4  0     
 3  22.8     4  108     93  3.85  2.32  18.6     1     1     4     1 NA     
 4  21.4     6  258    110  3.08  3.22  19.4     1     0     3     1  0.0190
 5  18.7     8  360    175  3.15  3.44  17.0     0     0     3     2 NA     
 6  18.1     6  225    105  2.76  3.46  20.2     1     0     3     1 -0.154 
 7  14.3     8  360    245  3.21  3.57  15.8     0     0     3     4 -0.235 
 8  24.4     4  147.    62  3.69  3.19  20       1     0     4     2  0.0702
 9  22.8     4  141.    95  3.92  3.15  22.9     1     0     4     2 -0.0656
10  19.2     6  168.   123  3.92  3.44  18.3     1     0     4     4  0.0608
# … with 22 more rows
  •  Tags:  
  • r
  • Related