Home > Mobile >  Using for loops to run through two different sequences of values in an equation
Using for loops to run through two different sequences of values in an equation

Time:04-28

New to R! My goal is to simultaneously change the values of two variables (i and j) in an equation, using two different sequences of numbers (x and y). I want to move through the for loops at the same time in order to go through each sequence of numbers once. Here's the code I've written so far:

A <- -13
B <- -21
x <- seq(from = 0, to = 10)/10
y <- seq(from = 10, to = 0)/10
for(i in x){
    for(j in y){
       SOM <- (A*i)   (B*j) 
       print (SOM)
    }
 }

I want i to go from 0 to 1 while j goes from 1 to 0, resulting in a list of 11 numbers that are the product of (A * i) (B * j). For example, when i = .2 and j is .8, SOM = -19.4. Right now, I think the code goes through each for loop separately or only for a part of the equation, which isn't what I want. Sorry in advance if there is an easy/obvious solution or if this isn't clear, I've never used R/programming for more than graphing data and would greatly appreciate any and all comments!

CodePudding user response:

These are arithmetic operations that are vectorized. There is no need for a loop if the intention is to get the output with length equal to that of the length of 'x' or 'y' (both considered to be of same length)

A * x   B * y

CodePudding user response:

Take advantage of the fact that y = 1-x:

B <- -21
x <- seq(from = 0, to = 10)/10

for(i in x){
       SOM <- (A*i)   (B*(1-i)) 
       print (SOM)
 }
  •  Tags:  
  • r
  • Related