Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R - Multiple variables in for loop?

Tags:

for-loop

r

How can I create a for loop in R which considers two variables?

Something like:

for(i in 1:10, j in 1:10) {
if vector[j] == vector2[i]
print(variable)
else print(NA) }

This should give me 100 outputs, as opposed to using

vector[i] == vector[i]

which would generate 10.

EDIT: Thanks for yor help so far. here is my actual data:

for(i in 1:10) {
    for(j in 1:10) {
        if (i == j)
        print(NA)
        else if(st231_eq1_alg$Output[j] == st231_eq1_alg$Input[i])
        print(st231_eq1_alg_f[i])
        else if(st231_eq1_alg$Output[j] == st231_eq1_alg$Output[i])
        print(st231_eq1_alg_inv_f[i])
        else print(NA)
    }
}

Any ideas how best to represent these outputs? Thanks again.

like image 759
Charlie Avatar asked Jul 29 '15 15:07

Charlie


3 Answers

It seems like you're asking about a nested for loop

for (i in 1:10){
  for(j in 1:10){
    ...
  }
}

But I would recommend a different approach

Vectors <- expand.grid(vector1 = vector1,
                       vector2 = vector2)
Vectors$comparison <- with(Vectors, vector1 == vector2)
like image 168
Benjamin Avatar answered Sep 23 '22 19:09

Benjamin


You can use outer to perform this and get a 10x10 matrix with the results:

vector <- 1:10
vector2 <- sample(vector)
outer(vector,vector2,"==")
       [,1]  [,2]  [,3]  [,4]  [,5]  [,6]  [,7]  [,8]  [,9] [,10]
 [1,] FALSE FALSE FALSE FALSE FALSE  TRUE FALSE FALSE FALSE FALSE
 [2,] FALSE FALSE  TRUE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
 [3,] FALSE FALSE FALSE FALSE  TRUE FALSE FALSE FALSE FALSE FALSE
 [4,] FALSE FALSE FALSE FALSE FALSE FALSE  TRUE FALSE FALSE FALSE
 [5,]  TRUE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
 [6,] FALSE  TRUE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
 [7,] FALSE FALSE FALSE  TRUE FALSE FALSE FALSE FALSE FALSE FALSE
 [8,] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE  TRUE FALSE
 [9,] FALSE FALSE FALSE FALSE FALSE FALSE FALSE  TRUE FALSE FALSE
[10,] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE  TRUE
like image 25
James Avatar answered Sep 22 '22 19:09

James


You could do this with nested for loops:

for (i in 1:10) {
  for (j in 1:10) {
    # Your logic in here
  }
}
like image 45
josliber Avatar answered Sep 21 '22 19:09

josliber