Indeed.
Start here:
http://www.r-bloggers.com/three-tips-for-posting-good-questions-to-r-help-and-stack-overflow/
and then read this:
http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example
Then put some comments into your code about what you think it should do. Oh, and
clean up the formatting.
Hope this helps.
B.
On Nov 19, 2014, at 11:29 PM, Esra Ulasan <esra_ulasan at icloud.com>
wrote:
> Dear Sir/Madam,
>
> I am a PhD candidate and writing my dissertation about portfolio
optimization in R. However, I have some problems with the codes. It always give
the dimension error. Could you help me to fix it?
>
> Yours sincerely,
>
> Here are the codes:
>
> optimization <- function(x) {
> mean <- colMeans(x)
> names(mean) <-assets.names
> p <- ncol(x)
> n <- nrow(x)
> M <- as.integer(p)
> S <- cov(x)
> invS<- solve(S)
> u <- rep(1,p)
>
> #w <- matrix(rep(0,p), nrow=p)
> #r <- seq(0,length=p); w <- cbind (diag(450)); #sum of 1
> #constraint <- cbind(diag(450), rep(0, 450)); #non-negativity
constraint
> a <- matrix(rep(0,4), nrow=2)
> a[1,1] <- u%*%invS%*%u;
> a[1,2] <- a[2,1] <- u%*%invS%*%mean
> a[2,2] <-mean%*%invS%*%mean
> d <- a[1,1]*a[2,2]-a[1,2]*a[1,2]
> f <- (invS%*%(a[2,2]*u-a[1,2]*mean))/d
> g <- (invS%*%(-a[1,2]*u+a[1,1]*mean))/d
> rho <- 0.5
> r <- seq(0, rho,length= M)
> w <- matrix(rep(0, p*M), nrow=p)
> for(m in 1:M) w[,m] <- f+r[,m]*g
> #w <- f+(rho*g)
> w[,m] >=0
> sum([,m])==1
> s <- sqrt(a[1,1]*((r-a[1,2]/a[1,1])^2)/d+ 1/a[1,1])
> ss <- sqrt(diag(S))
> names(ss) <- assets.name
> minp <- c(sqrt(1/a[1,1]), a[1,2]/a[1,1])
> wmimp<- f+(a[1,2]/a[1,1])*g;
> tanp <- c(sqrt(a[2,2])/a[1,2], a[2,2]/a[1,2])
> wtanp <- f+(a[2,2]/a[1,2])*g;
> return(solve(s, r, ss, p, minp, tanp, wminp, wtanp))
> }
> result=optimization(x)
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide
http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.