简体   繁体   English

R双环与哪里

[英]R double loop with where

I have the the following data frame and variables: 我有以下数据框和变量:

u0 <- c(1,1,1,1,1)
df <- data.frame (u0)
a = .793
b = 2.426
r = 0.243
q = 1
w = 2
j = 1
z = .314

using the following loop I am doing some calculations and put the results in the first row of my data frame. 使用以下循环我正在做一些计算,并将结果放在我的数据框的第一行。

while (j<5){
  df[q,w] <- df[q, w-1] * (r+j-1)*(b+j-1)*(z) / ((a+b+j-2)*j)
  j = j + 1
  w = w + 1
}

now I want to create another loop to do the same calculations for all rows (ie I need the 'q' variable to vary) of my data frame. 现在我想创建另一个循环来对我的数据帧的所有行(即我需要'q'变量变化)进行相同的计算。 I would be thankful if anyone helps me. 如果有人帮助我,我会感激不尽。

You could either do this by putting your while loop inside of a for loop that goes over q , but a more R-tastic way would be to simply define q <- 1:5 , and leave the rest of your code as-is. 您可以通过将while循环放在一个超过qfor循环中来实现这一点,但更简单的方法是简单地定义q <- 1:5 ,并保留其余的代码。 Then df will fill up entirely. 然后df将完全填满。 I take it in this example you want all rows to be identical? 我在这个例子中看到你希望所有行都相同吗?

Can't you just put it in a for loop? 你不能把它放在for循环中吗?

df <- data.frame (d1=u0, d2=u0+1, d3=u0+2, d4=u0+4, d5=u0+5)
for (q in 2:5) {
while (j<5){
  df[q,w] <- df[q, w-1] * (r+j-1)*(b+j-1)*(z) / ((a+b+j-2)*j)
  j = j + 1
  w = w + 1
           }    }

You may want to check the algorithm. 您可能想要检查算法。 It doesn't seem to be doing anything very interesting. 它似乎没有做任何非常有趣的事情。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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