lm() called within mutate()

末鹿安然 提交于 2019-12-01 18:28:42

This seems to work for me:

group_by(x, company) %>%
    do(data.frame(beta = coef(lm(return ~ market.ret,data = .))[2])) %>%
    left_join(x,.)
jlhoward

You seem to want to calculate a daily market return across all companies, and then regress return vs. market return for each company, across all days. If so, here's a solution using data.table; likely to be faster with very large datasets.

library(data.table) ## 1.9.2+
setDT(x)[ , market.ret := mean(return), by = date]
x[, beta := coef(lm(return ~ market.ret, data = .SD))[[2]], by = company]

where x is as shown below (using set.seed for reproducibility):

set.seed(1L)     # for reproducible example
n.dates <- 60
n.stocks <- 2
date <- seq(as.Date("2011-07-01"), by=1, len=n.dates)
symbol <- replicate(n.stocks, paste0(sample(LETTERS, 5), collapse = ""))
x <- expand.grid(date, symbol)
x$return <- rnorm(n.dates*n.stocks, 0, sd = 0.05)
names(x) <- c("date", "company", "return")
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!