简体   繁体   English

如何仅将一个向量的最后一个元素添加到另一个向量的最后一个元素?

[英]How do I add only the last element of one vector to the last element of another vector?

I have a dataframe with hundreds of different investments (represented by the "id" column), their cashflows, and market value.我有一个包含数百种不同投资(由“id”列表示)、它们的现金流和市场价值的数据框。 The following example demonstrates the data that I'm working with:以下示例演示了我正在使用的数据:

df <- data.frame(date = c("2020-01-31", "2020-02-29", "2020-03-31", "2020-02-29", "2020-03-31", "2020-04-30", "2020-05-31"),
                 id = c("alpha", "alpha", "alpha", "bravo", "bravo", "bravo", "bravo"),
                 cashflow = c(-100,20,4,-50,8,12,8),
                 market_value = c(100,90,80,50,110,120,115))

I ultimately want to calculate the IRR per investment.我最终想计算每笔投资的内部收益率。 However, before I can do that, I need to add only the last market value number to the corresponding cashflow.但是,在我这样做之前,我只需要将最后一个市值数字添加到相应的现金流中。 I don't care about any market values before that.在此之前我不关心任何市场价值。 In this case, the last cashflow for "alpha" investment must be 84 (ie, 80 market value + 4 cashflow) and the last cashflow for "bravo" investment must be 123 (ie, 115 market value + 8 cashflow).在这种情况下,“alpha”投资的最后现金流必须是 84(即 80 市值 + 4 现金流),而“bravo”投资的最后现金流必须是 123(即 115 市值 + 8 现金流)。

Desired output:期望的输出:

id ID cashflow现金周转
alpha α -100 -100
alpha α 20 20
alpha α 84 84
bravo好极了 -50 -50
bravo好极了 8 8
bravo好极了 12 12
bravo好极了 123 123

Thanks!谢谢!

I'm not too sure on what final output you want but here's how you'd just take the last.我不太确定你想要什么最终输出,但这是你如何选择最后一个。

df %>%
mutate(total = cashflow + market_value) %>%
group_by(id) %>%
slice_max(order_by = date) %>%
ungroup()

#> # A tibble: 2 × 5
#>   date       id    cashflow market_value total
#>   <chr>      <chr>    <dbl>        <dbl> <dbl>
#> 1 2020-03-31 alpha        4           80    84
#> 2 2020-05-31 bravo        8          115   123

Created on 2022-07-22 by the reprex package (v2.0.1)reprex 包于 2022-07-22 创建 (v2.0.1)

EDIT - just seen what I think is your desired output, how's this?编辑 - 刚刚看到我认为你想要的输出,这是怎么回事?

df %>%
  group_by(id) %>%
  mutate(
    cashflow = if_else(row_number() == n(), cashflow + market_value, cashflow)
  )
#> # A tibble: 7 × 4
#> # Groups:   id [2]
#>   date       id    cashflow market_value
#>   <chr>      <chr>    <dbl>        <dbl>
#> 1 2020-01-31 alpha     -100          100
#> 2 2020-02-29 alpha       20           90
#> 3 2020-03-31 alpha       84           80
#> 4 2020-02-29 bravo      -50           50
#> 5 2020-03-31 bravo        8          110
#> 6 2020-04-30 bravo       12          120
#> 7 2020-05-31 bravo      123          115

Created on 2022-07-22 by the reprex package (v2.0.1)reprex 包于 2022-07-22 创建 (v2.0.1)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM