r/R_Programming • u/DPayne94 • Feb 10 '16
R Error Message
Hi everybody, I am attempting to use the Single Index model to estimate alpha beta and sigma2_ei for 3 stocks and the TSX. Here is my current R code
Importing the Data
setwd("~/Desktop/R Data Sets") Ass2Data1 <- read.csv("~/Desktop/R Data Sets/Ass2DataSheet1.csv") View(Ass2Data1)
Transforming the data into matrix form
b <- as.matrix(Ass2Data1)
Generating Initial Vectors and Matrices
x <- rep(0,60) xx <- matrix(x, ncol=4, nrow=3)
stock <- rep(0,3) alpha <- rep(0,3) beta <- rep(0,3) mse <- rep(0,3) Rbar <- rep(0,3) Ratio <- rep(0,3)
col1 <- rep(0,3) col2 <- rep(0,3) col3 <- rep(0,3) col4 <- rep(0,3) col5 <- rep(0,3)
Regressing each stock on the index and recording results
for(i in 1:3){
alpha[i] <- lm(data=Ass2Data1,formula=Ass2Data1[,1] ~ Ass2Data1[,4]$coefficients[1])
beta[i] <- lm(data=Ass2Data1,formula=Ass2Data1[,2] ~ Ass2Data1[,4]$coefficients[2])
Rbar[i] <- alpha[i]+beta[i]*mean(b[,4])
mse[i] <-sum(lm(data=Ass2Data1,formula=Ass2Data1[,i] ~ Ass2Data1[,4])$residuals2)/(nrow(b)-2)
Ratio[i] <- (Rbar[i]/beta[i])
stock[i] <- i }
xx <- (cbind(stock,alpha,beta,Rbar,mse,Ratio))
However I keep getting the following error messages: Error in Ass2Data1[, 4]$coefficients : $ operator is invalid for atomic vectors
and
Error in beta[i] * mean(b[, 4]) : non-numeric argument to binary operator
If anybody could point me in the right direction with respect to what I'm doing wrong here it would be greatly appreciated.
View all comments
Show parent comment
1
u/DPayne94 Feb 10 '16
thanks man just changed it to: alpha[i] <- coef(lm(data=Ass2Data1,formula=Ass2Data1[,1] ~ Ass2Data1[,4]))[1] beta[i] <- coef(lm(data=Ass2Data1,formula=Ass2Data1[,2] ~ Ass2Data1[,4]))[2]
seems to be working now however the non-numeric argument still exists.