简体   繁体   中英

Apply regression coefficients that have one answer per factor to many entries per factor in a dataframe in R

I have a dataframe that has a column for time, symbol, price, volatility. I use this dataframe to run a first pass OLS regression using dummy variables for the symbol

fit <- lm(volatility~factor(symbol) + 0

Then I want to use the coefficients from that regression in a second pass regression, so I save the coeffiecients of the regression to reuse and then I want to use that to scale volatility

scale <- summary(fit)$coefficients[,1]
yscale <- volatility/scale
fit2 <- lm(yscale~factor(time) + factor(symbol)*factor(time) + 0

The problem that I am having is that I want to use the factor coefficients that are applicable to each symbol. So in the original dataframe I want to divide the volatility by the coeffiecient that matches its symbol. So, if I have symbols, DDX, CTY, LOL then I want to divide DDX's volatility by the coefficient with factor DDX from the regression then do the same for CTY and LOL. Also, I need to figure out how to do the product in the second fit2 coefficient.

You should provide a reproducible example to get an exact answers. Here some data:

dat <- data.frame(volatility= rnorm(30),
                  symbol = sample(c('DDX', 'CTY', 'LOL'),30,rep=TRUE))
fit <- lm(volatility~factor(symbol) + 0,data=dat)
mm <- coef(fit)
names(mm) <- gsub('factor\\(symbol\\)','',names(mm))

I transform the names to get a pretty names that can be used later :

   CTY        DDX        LOL 
 -0.1991273  0.1331980 -0.1567511 

Then using transform , I divide each volatility with the corresponding coefficients:

transform(dat,vol.scale = volatility/mm[symbol],coef = mm[symbol])
      volatility symbol    vol.scale       coef
1  -0.592306253    DDX  -4.44680974  0.1331980
2   1.143486046    DDX   8.58485769  0.1331980
3  -0.693694139    LOL   4.42544868 -0.1567511
4  -0.166050131    LOL   1.05932325 -0.1567511
5   1.381900588    CTY  -6.93978353 -0.1991273
..............................

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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