JKFY13
JKFY13

Reputation: 77

For loop in R can't retrieve the number of rows in a dataframe

I am trying to use a for loop in R to get the number of rows in dataframes.

year1<-c("2001","2002","2003")
countries1<-c("Canada","USA","Mexico")
color1<-c("black","red","blue")

year2<-c("2010","2011","2012")
countries2<-c("France","Germany","Japan")
color2<-c("white","yellow","green")

df1<-data.frame(year1,countries1,color1)
df2<-data.frame(year2,countries2,color2)

for (i in c(df1,df2))
{
nb<-nrow(i)
print(nb)
}

I expect to get 3 and 3 (as each dataframe has 3 rows) but I get 6 "NULL" instead. Can you help me?

Upvotes: 1

Views: 43

Answers (1)

akrun
akrun

Reputation: 887028

We can place it in a list, loop through the list and print the number of rows

for(dat in list(df1, df2)) {nb <- nrow(dat); print(nb)}
#[1] 3
#[1] 3

The issue with concatenation (c) is - it unclasses the data.frame and convert it to a list of vector. As there are 3 columns each in the data.frame, it would be a list of length 6 (i.e. 6 vector`s)

str(c(df1, df2))
#List of 6
# $ year1     : Factor w/ 3 levels "2001","2002",..: 1 2 3
# $ countries1: Factor w/ 3 levels "Canada","Mexico",..: 1 3 2
# $ color1    : Factor w/ 3 levels "black","blue",..: 1 3 2
# $ year2     : Factor w/ 3 levels "2010","2011",..: 1 2 3
# $ countries2: Factor w/ 3 levels "France","Germany",..: 1 2 3
# $ color2    : Factor w/ 3 levels "green","white",..: 2 3 1

Upvotes: 1

Related Questions