[R] for loop with multiple conditions in R (e.g. for(i in x & j in y)

arun smartpink111 at yahoo.com
Sat Feb 22 03:05:33 CET 2014


Hi,
May be this helps:
res.i <- NULL
 for(i in seq_along(x)){ res.i <- c(res.i,x[i]-y[i])}

#or using your nested loop: 
res.ij <- NULL
 for(i in seq_along(x)){
 for(j in seq_along(y)){
 if(i==j){
 res.ij <- c(res.ij,x[i]-y[j])
 }
 }}

identical(x-y,res.i)
#[1] TRUE

identical(res.i,res.ij)
#[1] TRUE
A.K.

I need a for loop that pulls data from two different vectors. For example, suppose that my vectors were 
x <- c(1,2,3) 
y <- c(4,5,6) 
and I wanted a loop that woul take i in x and subtract it from j in y
 how would I do it? (i.e. 1-4,2-5,3-6). Note: I realize that for this 
silly example there are much better ways to do this than using a for 
loop, but the actual script that I am working with is much more 
complicated and really does needs to be a for loop, so if you would 
humor me and tell me how to write a loop for this example rather than 
recommending a better way to solve the example, I would appreciate it. 

I've tried the following line of code, but, as expected, it 
subtract each value of i from each value of j, which is not what I want,
 I want the first value of i subtracted from the first value of j, the 
second value of i from the second value of j, etc. 
res.i <- c(NULL) 
for(i in x){ 
  for(j in y){ 
  sol.i <- i-j 
  res.i <- c(res.i,sol.i)} 
  print(res.i)} 

thanks!



More information about the R-help mailing list