For-loop in a for-loop

Hello. I need to run a for-loop inside the other one:

f<-vector()


for (x in seq(1,2,0.1)){
  
  for (k in seq(4,5,0.1)){
  
  b<-5
  f<-c(f,k*x+b)
  }
  
}

However, when I run the code, only the outer loop works.
Coul you, please, tell me, where is the mistake in my code? And how can I fix it?

can you say more about what leads you to believe that 'only the outer loop works' ?

f<-vector()
for (x in 1:2){
  for (k in 100:101){ 
    f<-c(f,k*x)
  } 
}
f
 100 101 200 202

That's because I get results like these:

[1]  9.0  9.0  9.0  9.0  9.0  9.0  9.0  9.0  9.0  9.0  9.0  9.4  9.4  9.4  9.4  9.4  9.4  9.4
 [19]  9.4  9.4  9.4  9.4  9.8  9.8  9.8  9.8  9.8  9.8  9.8  9.8  9.8  9.8  9.8 10.2 10.2 10.2
 [37] 10.2 10.2 10.2 10.2 10.2 10.2 10.2 10.2 10.6 10.6 10.6 10.6 10.6 10.6 10.6 10.6 10.6 10.6
 [55] 10.6 11.0 11.0 11.0 11.0 11.0 11.0 11.0 11.0 11.0 11.0 11.0 11.4 11.4 11.4 11.4 11.4 11.4
 [73] 11.4 11.4 11.4 11.4 11.4 11.8 11.8 11.8 11.8 11.8 11.8 11.8 11.8 11.8 11.8 11.8 12.2 12.2
 [91] 12.2 12.2 12.2 12.2 12.2 12.2 12.2 12.2 12.2 12.6 12.6 12.6 12.6 12.6 12.6 12.6 12.6 12.6
[109] 12.6 12.6 13.0 13.0 13.0 13.0 13.0 13.0 13.0 13.0 13.0 13.0 13.0

Can you describe what you would like the results to be.
I guess you might have wanted a 2d matrix

Ideally I'd like to get something like a table (data frame), where each value of "f" will be matched with the corresponding combination of "x" and "k". In other words, it should be something like this:

x k f
1 4 ...
1 4.1 ...
1 4.2 ...
... ... ...
1 5 ...
1.1 4 ...
1.2 4 ...
... ... ...
2 4.9 ...
2 5 ...

If you want a data frame, I suggest you use the rep() function instead of a for loop.

DF <- data.frame(x = rep(seq(1,2,0.1), each = 11),
                 k = rep(seq(4,5,0.1), 11))
DF$f <- DF$x * DF$k + 5
head(DF)
#>   x   k   f
#> 1 1 4.0 9.0
#> 2 1 4.1 9.1
#> 3 1 4.2 9.2
#> 4 1 4.3 9.3
#> 5 1 4.4 9.4
#> 6 1 4.5 9.5

Created on 2020-10-12 by the reprex package (v0.3.0)

FJCC is better generally, but if you want to see how it could be done with a for loop (which is best avoided typically)

xvec <- seq(1,2,0.1)
kvec <- seq(4,5,0.1)
f <- matrix(nrow=length(xvec)*length(kvec)-1,ncol=3)
cnt <- 0
for (x in xvec){
  for (k in kvec){
    f[cnt,1] <- x 
    f[cnt,2] <- k
    f[cnt,3] <-k*x
    
    cnt <- cnt + 1
  } 
}

f

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.