user3390169 user3390169 - 1 month ago 16
R Question

R quadprog error: (list) object cannot be coerced to type 'double'

I am moving along in my understanding of R but I have hit another snag when it comes to portfolio optimization. I have a program that spits out .csv files for a portfolio of assets. The first is the portfolio's variance/covariance matrix: covar.csv and the second is the expected returns of the assets: fwdCost.csv. I am trying to set the returns equal to -2,200,000 minimize the risk to the portfolio (weights must be between 0 and 1). I think my problem has something to do with my .csv files but I cannot figure out why solve.QP doesn't like them.

> library(quadprog)
> dmat<-read.csv(file="C:/Users/Desktop/RFrontier/covar.csv", head=TRUE, sep=",")
> dvec<-matrix(0, 1,length(dmat))
> amat<-read.csv(file="C:/Users/Desktop/RFrontier/fwdCost.csv", header=TRUE, sep=",")
> amat<-t(amat)
> x<-matrix(0, length(dmat), length(dmat))
> diag(x)<-1
> amat<-cbind(amat,x)
> x<--x
> amat<-cbind(amat,x)
> bvec<-c(-2200000, rep(0, length(dmat)), rep(-1,length(dmat)))
> solve.QP(dmat, dvec, amat, bvec)


yields this error: Error in solve.QP(dmat, dvec, amat, bvec) :
(list) object cannot be coerced to type 'double'

Answer

The issue is with amat and dmat -- they are not matrices but data.frames. use:

# after reading them into R
amat <- as.matrix(amat)
dmat <- as.matrix(dmat)

Then you can transpose, and whateverelse you'd like.

You can confirm that this is the source of the error by any of the following:

is(amat)
is.data.frame(amat)
is.matrix(amat)

as.numeric(amat) 
## This should give you a similar error to the one you are seeing.