将结果从嵌套循环写入R中的另一个向量

0 r vector nested-loops

我对R很陌生,我正在苦苦挣扎.我有以下代码:

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
    }
}
Run Code Online (Sandbox Code Playgroud)

我对最后一行的所有内容感到满意,但不是将p_0yx%*%(log2(logvect))的值打印到屏幕上,而是将其存储为另一个向量.有任何想法吗?我尝试过类似于嵌套循环的方式,但似乎没有用.

谢谢

Joh*_*ohn 6

简要回答是首先声明一个变量.把它放在你发布的所有内容之前.我打算称之为临时.它将包含所有值.

temp <- numeric(1000)
Run Code Online (Sandbox Code Playgroud)

然后,而不是您的打印线使用

temp[t] <- p_0yx %*% log2(logvect)
Run Code Online (Sandbox Code Playgroud)

顺便说一句,你的代码做了一些奇怪的事情.看一下p_0y的第一个索引.它实际上是0,该矩阵中项目的索引.R开始索引为1.当您在该矩阵中创建行数时,使用max(y) - min(y).如果max为10且min为1,那么只有9行.我打赌你真的想加一个.此外,您的代码与所有不必要的while循环非常不相似.例如,您的整个最后一个循环(以及logvect的初始化)可以替换为:

logvect = (p_0yx)/(p_yx)
Run Code Online (Sandbox Code Playgroud)

但回到错误..还有一些Rness ......可以使用以下代码......

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
    }
Run Code Online (Sandbox Code Playgroud)

也许可以更正确地替换?

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)
Run Code Online (Sandbox Code Playgroud)

(类似地重新考虑其余代码也可以消除其余的循环)