Nrow with forloop

Screen Link:

#does not work!!!
   compare<-c(sat_results, demographics, demo_sat_left, demo_sat_right, demo_sat_full)
  
   for (df in compare) {
     print(nrow(df))
    }

What I expected to happen: I want to be able to count the number of rows in 6 data frames using a for loop, however it is not working. If I do nrow(df), I will get a value of null. If I do print(nrow(df). I will get the entire dataframe. If I do not do the for loop and I just do it individually it will work correctly. I do not understand Why this simply for loop will not work.

Is this part of Dataquest? If you have the screen/exercise link, I can have a look.

Assuming it’s this:

You’ll probably need to use list:

compare<-list(sat_results, demographics, demo_sat_left, demo_sat_right, demo_sat_full)

for (df in compare) {
  print(nrow(df))
}

From reading the documentation on c, it doesn’t seem the function preserves the dataframe. Instead, you get 73 lists which corresponds to 73 columns from all the data frames combined. list preserves the tibble dataframe, but c does not.

# use list
compare<-list(sat_results, demographics, demo_sat_left, demo_sat_right, demo_sat_full)

sum_cols<-0
for (df in compare) {
  print(ncol(df))
  print(class(df))
  sum_cols<- sum_cols + ncol(df)
}

# a list of 5 dataframes
print(length(compare))

# there are 73 cols
print(sum_cols)

# use c
compare_2<-c(sat_results, demographics, demo_sat_left, demo_sat_right, demo_sat_full)

# there are 73 lists of various types
print(length(compare_2))
2 Likes