Трудно разобрать, что именно вы ищете, и у меня нет финансовых знаний, но что-то вроде этого может помочь:
library(dplyr)
# High Returns
returnhigh <- df %>%
group_by(Company) %>%
filter(`Market Value` > 0) %>%
mutate(Weight = 1/length(Company)) %>%
ungroup() %>%
mutate(wt_return = Weight * Return)
# Low Returns
returnlow <- df %>%
group_by(Company) %>%
filter(`Market Value` < 0) %>%
mutate(Weight = 1/length(Company)) %>%
ungroup() %>%
mutate(wt_return = Weight * Return)
# Port Function to summarise your high and low returns
port_func <- function (x) {
x <- x %>%
group_by(Date) %>%
summarise(port_ret = sum(wt_return))
}
porthigh <- port_func(returnhigh)
portlow <- port_func(returnlow)
Вывод:
df <- structure(list(Company = c("Company x", "Company x", "Company x",
"Company x", "Company x", "Company x", "Company x", "Company x",
"Company x", "Company x", "Company x", "Company x"), Year = c(2008,
2008, 2008, 2008, 2008, 2008, 2008, 2008, 2008, 2008, 2008, 2008
), Score = c(26.26, 26.26, 26.26, 26.26, 26.26, 26.26, 26.26,
26.26, 26.26, 26.26, 26.26, 26.26), Date = c("2008-01-01", "2008-02-01",
"2008-03-01", "2008-04-01", "2008-05-01", "2008-06-01", "2008-07-01",
"2008-08-01", "2008-09-01", "2008-10-01", "2008-11-01", "2008-12-01"
), Return = c(-0.32, -0.1, -0.06, 0.01, 0.28, -0.25, 0.11, 0.15,
-0.12, -0.27, -0.25, -0.17), `Market Value` = c(601.26, 410.65,
369.8, 348.15, 353.1, 452.43, 338.91, 376.86, 433.62, 383.72,
281.95, 211.2)), row.names = c(NA, -12L), class = c("tbl_df",
"tbl", "data.frame"))