branchwarren branchwarren -4 years ago 109
R Question

apply model coefficients on new data

I have two matrices

sub
and
macro_data
. They include the estimated coefficients of a model and the macro data, respectively

> sub
coeff varname
1 -1.50 gdp
2 0.005 inflation
3 -2.4 constant

> macro_data
gdp inflation
1 18.0 -0.17
2 15.8 -0.14
3 17.7 -0.15


I would like to apply the following formula: -1.5*gdp+0.005*inflation-2.4 in order to get the scores.

I have tried

for (i in 1:1){
sub$coeff[i]*macro_data[,1]+sub$coeff[i+1]*macro_data[,sub$coeff[i+1]]+sub$coeff[i+2]
}


Actually it works but this is not the best solution, because I would like something general. Any idea?

Answer Source

You can do a matrix multiplication:

cbind(macro_data, 1) %*% sub[, "coeff", drop=FALSE]

If your coefficients are from estimating a model, then normally the function predict.~() can take a parameter newdata= to claculate estimates for new data.

For your example data this wont work because you have dataframes. This will do:

sub <- read.table(header=TRUE, text=
"coeff      varname
 -1.50          gdp      
  0.005         inflation     
 -2.4           constant ")

macro_data <- read.table(header=TRUE, text=
"gdp        inflation 
1   18.0      -0.17  
2   15.8      -0.14 
3   17.7      -0.15")

m <- cbind(macro_data, constant=1)
C <- sub$coeff
names(C) <- sub$varname
m$gdp * C["gdp"] + m$inflation*C["inflation"] + m$constant*C["constant"]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download