rfor-loopdifference-between-rows

Difference between nrow and length in for loop?


It might be a stupid question, but I dont seem to understand why the nrow and length vectors are behaving differently.

Example:

   #Create a dummy data frame
   dff = data.frame(X = c(35,18,17,35), Y =c(1,2,3,4))

   #Test whether 1:nrow(dff) and 1:length(dff[,1]) are identical

   identical(1:nrow(dff), 1:length(dff[,1]))
   #[1] TRUE

   #Run a nested for-loop 
    step1 = matrix(0, nrow=nrow(dff), ncol = nrow(dff)) #create a placeholder
    for (i in 1:nrow(dff)) {# for each row in the first column 
      for (j in 1:nrow(dff)) { # for each row in the second column 
    step1[i, j] <-  dff$Y[i] + dff$X[j] # add them in the placeholder
        }
      }

     #       [,1] [,2] [,3] [,4]
     # [1,]   36   19   18   36
     # [2,]   37   20   19   37
     # [3,]   38   21   20   38
     # [4,]   39   22   21   39

    # Now run the same example using 1:length(dff[,1])

    step1 = matrix(0, nrow=nrow(dff), ncol = nrow(dff)) #create a placeholder
    for (i in 1:length(dff[,1])) {# for each row in the first column 
      for (j in 1:length(dff[,2])) { # for each row in the second column 
    step1[i, j] <-  dff$Y[i] + dff$X[j] # add them in the placeholder
       }
    }

   #       [,1] [,2] [,3] [,4]
   # [1,]    0    0    0    0
   # [2,]    0    0    0    0
   # [3,]    0    0    0    0
   # [4,]    0    0    0    0

What is difference? Why am I getting two different answers, please give a dummy explanation. Thanks


Solution

  • There is a typo in your code:

    As Patronus stated do the following:

      step2 = matrix(0, nrow=nrow(dff), ncol = nrow(dff)) #create a placeholder
      for (i in 1:length(dff[,1])) {# for each row in the first column 
        for (j in 1:length(dff[,2])) { # for each row in the second column 
      step2[i, j] <-  dff$Y[i] + dff$X[j] # add them in the placeholder
           }
       }
      #       [,1] [,2] [,3] [,4]
      # [1,]   36   19   18   36
      # [2,]   37   20   19   37
      # [3,]   38   21   20   38
      # [4,]   39   22   21   39