Search code examples
rfor-looprow

For loop for counting the number of rows per table in a list


I need to count the number of rows per table in a list containing several tables. I have written a loop but it cannot do what I desire: Here is my dummy data:

obj1 <- list(bodyPart = c("leg", "arm", "knee"),side = c("LEFT", "RIGHT", "LEFT"), device = c("LLI", "LSM", "GHT"), id = c("AA", "BB", "CC")) %>%  as.data.frame()
obj2 <- list(bodyPart = c("leg", "arm", "knee"), side = c("LEFT", "LEFT", "LEFT"), device = c("GOM", "LSM", "YYY"), id = c("ZZ", "DD", "FF")) %>%  as.data.frame()

x <- list(M = obj1, B = obj2)

And the for loop:

for (table in names(x)) {
  print(table)
print(nrow(table))  
}

I expect the output to be the number of rows per table (M = 3, B = 3) but it just yields NULL per table. Could you please correct me? Thanks in advance!


Solution

  • You should use x[[table]] to index the elements in x

    for (table in names(x)) {
        print(table)
        print(nrow(x[[table]]))
    }
    

    which gives

    [1] "M"
    [1] 3
    [1] "B"
    [1] 3
    

    Otherwise, table is just the names in your list x, not the contents as it refers to.