Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading