如何将函数应用于数据框,然后应用于数据框列表?

How do I apply a function to a dataframe and then to a list of dataframes?

我需要计算多个投资组合的滚动三个月 return。我想应用一个函数来实现这一点,因为我有几个投资组合和基准来计算它。

为了我的理解

数据框

    stefi <- tibble::tribble(    ~date ,  ~return,
                           1996-04-30,   0.0126,
                           1996-05-31,   0.0126,
                           1996-06-30,   0.0119,
                           1996-07-31,   0.0144,
                           1996-08-31,   0.0132,
                           1996-09-30,   0.0136,
                           1996-10-31,   0.0135,
                           1996-11-30,   0.0127,
                           1996-12-31,   0.0143,
                           1997-01-31,   0.0144)

我的函数尝试

这是我计算三个月 return 的函数。数学很好,但我不确定它是否应该 return 向量、变量或其他东西,以达到我需要使用的 apply 方法的目的。

    calc_3m_return <- function(x){
      
      y <- (x + 1) *
        ((lag(X, 1)) + 1) *
        ((lag(X, 2)) + 1) - 1
      
      return(y)
      
    }

我在 applylapply 方面运气不佳。

lapply(stefi$return, calc_3m_return, return)

R的输出

> lapply(stefi$return, calc_3m_return, return)
Error in FUN(X[[i]], ...) : unused argument (return)

我能得到什么工作

我通过以下步骤设法获得了想要的结果:

#Calculate return function
calc_3m_return <- function(return){
  
  y <- (return + 1) *
    ((lag(return, 1)) + 1) *
    ((lag(return, 2)) + 1) - 1
  
  return(y)
  
}

#Calculate 3-month return and append it to the dataframe
stefi <- stefi %>%
  mutate(return_3m = calc_3m_return(return))

结果

# A tibble: 6 x 3
  date       return return_3m
  <date>      <dbl>     <dbl>
1 1996-04-30 0.0126   NA     
2 1996-05-31 0.0126   NA     
3 1996-06-30 0.0119    0.0376
4 1996-07-31 0.0144    0.0395
5 1996-08-31 0.0132    0.0401
6 1996-09-30 0.0136    0.0418

可能的解决方案(ldf 包含所需的数据帧列表):

library(tidyverse)

stefi <- tibble::tribble(    ~date ,  ~return,
                             1996-04-30,   0.0126,
                             1996-05-31,   0.0126,
                             1996-06-30,   0.0119,
                             1996-07-31,   0.0144,
                             1996-08-31,   0.0132,
                             1996-09-30,   0.0136,
                             1996-10-31,   0.0135,
                             1996-11-30,   0.0127,
                             1996-12-31,   0.0143,
                             1997-01-31,   0.0144)
ldf <- list(stefi,stefi)

calc_3m_return <- function(x){
  
  y <- (x + 1) *
    ((lag(x, 1)) + 1) *
    ((lag(x, 2)) + 1) - 1
  
  return(y)
}

map(ldf, ~ {.x$return_3m <- calc_3m_return(.x$return); .x})

# Or alternatively
# map(ldf, ~ tibble(.x, return_3m = calc_3m_return(.x$return)))