我正在嘗試計算資料框中幾家公司的 TPVI [(當前價值 股息)/投資]。
我的資料框看起來像這樣(此示例中的日期不準確)
| 公司 | 日期 | 公制 | 價值 |
|---|---|---|---|
| 公司1 | 11-15-2015 | 投資 | 100 |
| 公司1 | 11-15-2015 | 當前值 | 120 |
| 公司1 | 11-15-2015 | 股息 | 5 |
| 公司2 | 11-15-2015 | 投資 | 200 |
| 公司2 | 11-15-2015 | 當前值 | 120 |
| 公司2 | 11-15-2015 | 股息 | 30 |
| ... | ... | ... | ... |
我正在嘗試將值排序到一個新的資料框中,如下所示:
| 公司 | 日期 | TVPI |
|---|---|---|
| 公司1 | ... | ... |
| 公司1 | ... | ... |
| 公司1 | ... | ... |
| 公司1 | ... | ... |
| 公司2 | ... | ... |
| 公司2 | ... | ... |
| 公司2 | ... | ... |
即每個唯一公司/日期配對的新 TVPI 行。
我努力了
df %>% group_by(Date, Metric) %>% summarize()
但我不確定如何確定要總結的正確值(在示例資料框中,第一個 tpvi 將是 (120 5)/100。由于每個公司/日期配對都有三個“值”要跟蹤,因此語法我不知道如何在summarize函式中用這個詞。任何幫助表示贊賞。
uj5u.com熱心網友回復:
對不同的 s 輕松執行計算的一種方法Metric是拳頭tidyr::pivot_wider(),使它們各自成為一個單獨的列,然后使用您的公式創建一個新列dplyr::mutate()。如果您還提供.keep = "unused"給mutate()它,它將只留下您在所需輸出中指定的列。此外,我將您的Date列轉換為實際date格式而不是 a character,這將使其x在圖中作為軸值表現得更好。然后你可以直接進入繪圖。這個例子很無聊,因為你只提供了一個Date,但這Company顯示了一般的想法。
library(tidyverse)
d <- structure(list(Company = c("Company1", "Company1", "Company1", "Company2", "Company2", "Company2"), Date = c("11-15-2015", "11-15-2015", "11-15-2015", "11-15-2015", "11-15-2015", "11-15-2015"), Metric = c("invested", "current value", "dividends", "invested", "current value", "dividends"), Value = c(100L, 120L, 5L, 200L, 120L, 30L)), class = "data.frame", row.names = c(NA, -6L))
d %>%
pivot_wider(names_from = Metric, values_from = Value) %>%
mutate(TPVI = (`current value` dividends)/invested, .keep = "unused",
Date = as.Date(Date, format = "%m-%d-%Y")) %>%
ggplot(aes(Date, TPVI, color = Company))
geom_point()
geom_line()

由reprex 包于 2022-02-21 創建(v2.0.1)
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/430459.html
上一篇:R:將坐標轉換為“行程”
