-1

Here is what I want to do:

I have a time series data frame with let us say 100 time-series of length 600 - each in one column of the data frame.

I want to pick up 10 of the time-series randomly and then assign them random weights that sum up to one. Using those I want to compute the variance of the sum of the 10 weighted time series variables (e.g. convex combination).

The df is in the form

v1,v2,v2.....v100
1,5,6,.......9
2,4,6,.......10
3,5,8,.......6
2,2,8,.......2
etc

i can compute it inside a loop but r is vector oriented and it is not efficient.

ntrials = 10000
ts.sd = NULL
for (x in 1:ntrials))
  {
  temp = t(weights[,x]) %*% cov(df[, samples[, x]]) %*% weights[, x]
  ts.sd = cbind(ts.sd, temp)
  }
1
  • Well, I explicitly requested you to ask new questions. However, as far as I am aware the answer to that question was already given in stackoverflow.com/questions/13553943/… - only in words, not in code, though.
    – Thilo
    Nov 29, 2012 at 13:55

1 Answer 1

1

Not sure what type of "random" you want for your weights... so I'll use a normal distribution scaled s.t. it sums to one:

x=as.data.frame(matrix(sample(1:20, 100*600, replace=TRUE), ncol=100))

myfun <- function(inc, DF=x) {
  w = runif(10)
  w = w / sum(w)
  t(w) %*% cov(DF[, sample(seq_along(DF), 10)]) %*% w
}

lapply(1:ntrials, myfun)

However, this isn't really avoiding loops per say since lapply is just an efficient looping construct. That said, for loops in R aren't explicitly bad or inefficient. Growing a data structure, like you're doing with cbind, however, is.

But in this case since you're only growing it by appending a single element it really wont change things much. The "correct" version would be to pre-allocate your vector ts.sd using ntrials.

ts.sd = vector(mode='numeric', length=ntrials)

The in your loop assign into it using i:

for (x in 1:ntrials))
  {
  temp = t(weights[,x]) %*% cov(df[, samples[, x]]) %*% weights[, x]
  ts.sd[i] = temp
  }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.