I'm new to R and I'm trying to understand how loops work in R. But I just can't figure out how to make them work when there are 2 (or more) of them.
Here is the code:
for (i in 1:(length(b)-1))
{
for (j in 1:(length(a))
{
if ((a[j] >= b[i]) && (a[j] <b[i+1]))
{
1
}
else
{
0
}
}
}
a and b are two vectors.
So (in case the code is not clear - which is certainly the case) all i want is that the condition tests for i=1 then goes through all j's. Then tests for i=2 and goes through all j's. Etc. And when the condition is ok, returns 1, otherwise 0.
All i want is an output with a matrix/vector of 0's and 1's. 1 when the condition is respected, 0 when it isn't. About the inputs, "a" could be (0,0.01,0.02,...,0.99) and "b" could be (0,0.1,0.2,...,1). If you find/know a way without loops, that would be great too.
Thank you for your help. Sorry if this has already been asked. I'm fairly new to this.
EDIT : @alexis_laz I didn't think about pre-allocating a matrix. That could do the trick. Thank you, a lot. However, when I try this function:
test <- function(a,b)
{
mat <- matrix(,length(a), (length(b)-1))
for (i in 1:(length(b)-1))
{
for (j in 1:length(a))
{
if ((a[j] >= b[i]) && (a[j] <b[i+1]))
{
mat[j,i] = 1
}
else
{
mat[j,i] = 0
}
}
}
}
Litteraly nothing happens (no errors, the matrix is not filling in, etc.). I tried it with 2 vectors (the same defined earlier). Is there something wrong with this function ? Something I don't understand ? (I'm really new to R, sorry if all my questions seem stupid or unclear.)