【问题标题】:Calculate mean by going forward without for loop [duplicate]通过在没有for循环的情况下继续计算平均值[重复]
【发布时间】:2018-07-12 09:57:09
【问题描述】:

我的数据框如下所示:

BookValue  Maturity   Yield  Weight
   20      2018     4.000  0.00282
   30      2019     4.550  0.00424
   70      2026     1.438  0.00989
   80      2026     1.438  0.01131
   60      2043     0.000  0.00848
   40      2043     0.000  0.00565

我想通过每一步减少一年来计算所有年份的总账面价值的总和,以获得以下输出:

Year       Book Value
2018-2043     300 
2019-2043     280
2026-2043     250
2043          100

这怎么可能?没有for循环是否可能?

【问题讨论】:

    标签: r


    【解决方案1】:

    通过base的方式,你可以使用rev()和cumsum()。

    val <- tapply(df$BookValue, df$Maturity, sum)
    rev(cumsum(rev(val)))
    
    # 2018 2019 2026 2043 
    #  300  280  250  100
    

    数据

    df <- data.frame(BookValue = c(20, 30, 70, 80, 60, 40),
                     Maturity = c(2018, 2019, 2026, 2026, 2043, 2043))
    

    【讨论】:

    • 完美,非常感谢。
    • @Christian 如果我的回答解决了您的问题,请单击旁边的复选标记将其标记为已接受。谢谢!
    【解决方案2】:

    这是使用base 函数的可能方法:

    #aggregate by year first
    ans <- aggregate(dat$BookValue, list(dat$Maturity), sum)
    N <- nrow(ans)
    
    #then sum from 1:N, 2:N, 3:N, and so on
    if (nrow(ans) >= 1) {
        ans$BVSum <- sapply(1:N, function(n) sum(ans$x[ n:N ]))
    }
    

    数据:

    dat <- read.table(text="BookValue  Maturity   Yield  Weight
    20      2018     4.000  0.00282
    30      2019     4.550  0.00424
    70      2026     1.438  0.00989
    80      2026     1.438  0.01131
    60      2043     0.000  0.00848
    40      2043     0.000  0.00565", header=TRUE)
    

    【讨论】:

      【解决方案3】:

      另一种选择:

      # Assuming df is in order we extract first row for each year:
      frow <- which(!duplicated(df$Maturity))
      n <- nrow(df)
      
      
      tbv <- lapply(
        frow, 
        function(x) {
          data.frame(
            year = paste0(df$Maturity[x], "-", df$Maturity[n]),
            book_value = sum(df$BookValue[x:n])
          )
        }
      )
      do.call(rbind, tbv)
             year book_value
      1 2018-2043        300
      2 2019-2043        280
      3 2026-2043        250
      4 2043-2043        100
      

      【讨论】:

        猜你喜欢
        • 2021-04-17
        • 2016-12-22
        • 1970-01-01
        • 1970-01-01
        • 2016-10-31
        • 2021-01-29
        • 2021-02-02
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多