0

I want to multiply regression coefficients with the actual variables for every observation. Without factors, I can do this by multiplying the matrix of variables element wise with the vector of coefficients

v_coef <- as.matrix(vars) %*% as.matrix(coef)

However, the problem I am facing is that one of my variables is a factor. Therefore, the regression returns multiple coefficients associated with dummy variables (one for every year with one year excluded). Therefore, the line of code above does not work anymore as several coefficients are associated with the same column in the matrix of variables.

### Working example
# Make up dataframe
df      <- data.frame(matrix(rnorm(6*1000, 1, .5), ncol=6))
# Make up some years (3)
df$year <- c(rep(1,333),rep(2,333),rep(3,334))
# Regress something with years as factor
model   <- lm(X1~X2+X3+X4+X5+X6+factor(year),data=df)
# This does not work because years receive 3 coefficients for 1 column
m_coef  <- as.matrix(df) %*% as.matrix(model$coefficients)

I see two solutions, however, cannot figure out how to implement them. Either, I split the factor column into several columns with 0's for all except the applicable year and 1's for the observations that fall within that year. Alternatively, I change the matrix multiplication and assign the coefficients to different values of the factor

Kevin
  • 61
  • 4

1 Answers1

2
df      <- data.frame(matrix(rnorm(6*1000, 1, .5), ncol=6))

year <- c(rep(1,333),rep(2,333),rep(3,334))
df$year1 = ifelse(year == 1, 1, 0)
df$year2 = ifelse(year == 2, 1, 0)

model  <- lm(X1~X2+X3+X4+X5+X6+year1+year2,data=df)

m_coef  <- as.matrix(df) %*% model$coefficients

Add dummy variables for the factors levels - you do not need to specify year3 as it is represented by the case year1 == 0 and year2 == 0. Also add as.matrix to df in matrix multiplication.

Edit: For larger factors use model.matrix()

dummies = model.matrix(~as.factor(year))[,-1]

The first column is the intercept which can be ignored as it is specified by the other columns as previously stated.

Adam Waring
  • 1,158
  • 8
  • 20