Optimal weights for portfolio optimisation (r)

The question is what R optimization could be applicable to find a vector of weights that when, multiplied by S matrix creates equal rows sums, and when set in the objective function returns the minimal value.
The code will be reused for different number and combination of assets.
n = number of assets
x = vector of weights per asset (the solution of the optimization X1,…,Xn) #unknown
R = matrix of returns for n number of assets
S = a given matrix of numbers with 2 rows and n columns
Objective: minimize the fun.obj

fun.obz <- function(R, x, na.rm = TRUE) {
covmat <- var(R = R, na.rm = na.rm)
utc <- upper.tri(covmat)
wt.var <- sum(diag(covmat) * x^2)
wt.cov <- sum(x[row(covmat)[utc]] *
x[col(covmat)[utc]] *
covmat[utc])
variance <- wt.var + 2 * wt.cov
return(variance)  }

Constraints:
The sum of x == 1
Each x >= 0 #positive
S[1,] == S[2,] meaning S[1,]-S[2,] == 0 # the sum of each column is equal or with a small tolerance.

Create data

library('Quandl')
a1 = Quandl("YAHOO/AAPL", transform ="rdiff", start_date="2013-12-31", type="xts")
a2 = Quandl("YAHOO/GOOG", transform ="rdiff", start_date="2013-12-31", type="xts")
a3 = Quandl("YAHOO/MSFT", transform ="rdiff", start_date="2013-12-31", type="xts")

a4 = Quandl("YAHOO/HPQ", transform ="rdiff", start_date="2013-12-31", type="xts")
a5 = Quandl("YAHOO/ORCL", transform ="rdiff", start_date="2013-12-31", type="xts")
R = merge(a1$Adjusted Close,a2$Adjusted Close,a3$Adjusted Close,a4$Adjusted Close, a5\$Adjusted Close, all=TRUE)
colnames(R) = c('AAPL','GOOG','MSFT','HPQ','ORCL')
n = ncol(R)
S = matrix( c(-0.003296857,-0.003361181,-0.005320475,0.001920951,-0.0017016479,-0.005304732, -0.007212091,-0.003841529,0.004978937,-0.0001444762), byrow=TRUE, ncol=5)
colnames(S) = c('AAPL','GOOG','MSFT','HPQ','ORCL')
rownames(S) = c('S1','S2')
• This seems like a standard optimization problem, which probably "textbook solutions" which I would search. Technically, it seems like your objective function is a quadratic expression of the form t(x)Rx or something very similar to it, and your constraint is the null space of the matrix S or some variations of it. sounds like you'll find directions in any standard (possibly advanced level) linear algebra textbook. – amit Jan 30 '17 at 21:00