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.
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)
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
You could do this with nested for loops:
for (i in 1:10) {
for (j in 1:10) {
# Your logic in here
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With