Max
Max

Reputation: 37

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

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!

Upvotes: 2

Views: 222

Answers (2)

akrun
akrun

Reputation: 887153

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

Upvotes: 0

Jonathan Graves
Jonathan Graves

Reputation: 146

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)
 }

Upvotes: 0

Related Questions