user975790
user975790

Reputation: 1

Writing the results from a nested loop into another vector in R

I'm pretty new to R, and am struggling a bit with it. I have the following code:

repeat {
    if (t > 1000) 
        break
    else {
        y1 <- rpois(50, 15)
        y2 <- rpois(50, 15)
        y <- c(y1, y2)
        p_0y <- matrix(nrow = max(y) - min(y), ncol = 1)
        i = min(y)
        while (i <= max(y)) {
            p_0y[i - min(y), ] = (length(which(y1 == i))/50)
            i <- i + 1
        }
        p_y <- matrix(nrow = max(y) - min(y), ncol = 1)
        j = min(y)
        while (j <= max(y)) {
            p_y[j - min(y), ] = (length(which(y == j))/100)
            j <- j + 1
        }
        p_0yx <- p_0y[rowSums(p_0y == 0) == 0]
        p_yx <- p_y[rowSums(p_0y == 0) == 0]
        g = 0
        logvect <- matrix(nrow = (length(p_yx)), ncol = 1)
        while (g <= (length(p_yx))) {
            logvect[g, ] = (p_0yx[g])/(p_yx[g])
            g <- g + 1
        }
        p_0yx %*% (log2(logvect))
        print(p_0yx %*% (log2(logvect)))
        t <- t + 1
    }
}

i am happy with everything up to the last line, but instead of printing the value of p_0yx%*%(log2(logvect)) to the screen i would like to store this as another vector. any ideas? i have tried doing it a similar way as in the nested loop but doesnt seem to work.

Thanks

Upvotes: 0

Views: 678

Answers (1)

John
John

Reputation: 23758

The brief answer is to first declare a variable. Put it before everything you've posted here. I'm going to call it temp. It will hold all of the values.

temp <- numeric(1000)

Then, instead of your print line use

temp[t] <- p_0yx %*% log2(logvect)

As an aside, your code is doing some weird things. Look at the first index of p_0y. It is effectively an index to item 0, in that matrix. R starts indexing at 1. When you create the number of rows in that matrix you use max(y) - min(y). If the max is 10 and the min is 1 then there's only 9 rows. I'm betting you really wanted to add one. Also, your code is very un R-like with all of the unnecessary while loops. For example, your whole last loop (and the initialization of logvect) can be replaced with:

logvect = (p_0yx)/(p_yx)

But back to the errors.. and some more Rness... could the following code...

p_0y <- matrix(nrow = max(y) - min(y), ncol = 1)
i = min(y)
while (i <= max(y)) {
    p_0y[i - min(y), ] = (length(which(y1 == i))/50)
    i <- i + 1
    }

maybe be replaced more correctly with?

p_0y <- numeric(max(y) - min(y) + 1)
p_0y[sort(unique(y1)) - min(y1) + 1] = table(y1)/50
p_0y <- matrix(p_0y, ncol = 1)

(similar rethinking of the rest of your code could eliminate the rest of the loops as well)

Upvotes: 6

Related Questions