Search code examples
rloopsnested-loops

How to loop through two variables at once in r


I am trying to loop through 2 variables together in R.

Here is what I have

for (x in c(gl_50, gl_100, gl_200,gl_300,gl_400,gl_500,gl_600, gl16)) {
     for (y in c(50, 100, 200, 300, 400, 500, 600, 670)) {
  gi_x <- gl2gi(x)
  sum_x <- basic.stats(gi_x)
  
  ind<-colMeans(sum_x$n.ind.samp, na.rm=T)
  Ho<-colMeans(sum_x$Ho, na.rm = T)
  Hs<-colMeans(sum_x$Hs, na.rm = T)
  Fis<-colMeans(sum_x$Fis, na.rm = T)

  sum<-data.frame(cbind(ind, Ho, Hs, Fis))
  sum$snp_no <- rep(y)
  print(sum)

The current result is the loop runs gl_50 with all values of y then gl_100 with all values of y and so on. What I want is gl_50 with 50, gl_100 with 100, gl_200 with 200 and so on.


Solution

  • Generally, you should loop through their indices and access them like:

    a <- c(gl_50, gl_100, gl_200,gl_300,gl_400,gl_500,gl_600, gl16)
    b <- c(50, 100, 200, 300, 400, 500, 600, 670)
    for (i in seq_along(a)) {
      a[i] 
      b[i]  
    }