简体   繁体   中英

Save correlation output from loop to matrix

I have a setup that looks like below

for(V in (seq(1, 250, by = 5))){
   for(n in (seq(1, 250, by = 5))){

        # 1) Working Algorithm creating a probability 
             ie. vector in range [0:1] 

        # 2) Take the natural log of this probability 
        a <-  log(lag(Probability), base = exp(1))

        # 3) calculate price differences
        b <-  abs(diff(Price) -1)

        # 4) Then compute correlation between a and b
        cor(a, b) 

        # 5) Here I'd like to save this in the corresponding index of matrix
   }
}

So that I get a [V, n] sized matrix as output, that collects from each loop.

I have a few problems with this.

  • The first problem is that my correlation is not computable, as the Probability is often 0, creating a ln(0) = -Inf input in the ln(Probability) vector. Is there a way to compute the std.dev or cor of a Ln vector with -Inf inputs?

  • My second question is how I save this correlation output into a matrix generated for each loop?

Thanks for your help. I hope this is clear enough.

What you can do with -Inf is replace that by NA, for example:

x = runif(10)
x[3] = 1/0
> is.infinite(x)
 [1] FALSE FALSE  TRUE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
x[is.infinite(x)] <- NA
> x
 [1] 0.09936348 0.66624531         NA 0.90689357 0.71578917 0.14655174
 [7] 0.59561047 0.41944552 0.67203026 0.03263173

And use the na.rm argument for sd :

>  sd(x, na.rm = TRUE)
[1] 0.3126829

For your second question (My second question is how I save this correlation output into a matrix generated for each loop?), you could initialise a matrix before the loop and store each computed correlation in the corresponding index like:

sz <- seq(1, 250, by = 5)
out_mat <- matrix(0, nrow=length(sz), ncol=length(sz))
# then continue with your for-loop
for (V in 1:length(sz)) {
    for(n in length(sz)) {
        # here instead of accessing V and n in computing probability
        # use sz[V] and sz[n]
        ...
        ...
        # after computing the correlation, here use V and n (not sz[V] or sz[n])
        out_mat[V, n] <- c # c holds the value of cor(a,b)
    }
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM