Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to count rows?

Tags:

list

dataframe

r

I have simple question (at least not for me ..). I have been ended with list with multiple dataframes of different length. I want to count length of each dataframe..

mylist <- list (a = data.frame(i = 1:10, j= 11:20), b = data.frame(i = 1:5, j= 11:15), c = data.frame(i = 1:8, j= 11:18))
mylist
$a
    i  j
1   1 11
2   2 12
3   3 13
4   4 14
5   5 15
6   6 16
7   7 17
8   8 18
9   9 19
10 10 20

$b
  i  j
1 1 11
2 2 12
3 3 13
4 4 14
5 5 15

$c
  i  j
1 1 11
2 2 12
3 3 13
4 4 14
5 5 15
6 6 16
7 7 17
8 8 18

My poor codes:

lapply(mylist, function(y)length(y) 

$a
[1] 2

$b
[1] 2

$c
[1] 2

Oh....no..... How can I count number of rows in each component dataframe and get a new vector with:

 # number of rows in each component dataframe of the list 
 myvec
[1] 10  5  8

Thank you for your time...I appreciate it...

like image 551
John Clark Avatar asked Sep 07 '11 20:09

John Clark


1 Answers

Try this:

myvec <- sapply(mylist, NROW)

length gives "odd" results with data.frames because data.frames are really lists of vectors of the same length. length(data.frame) is giving you the length of the underlying list, which is the number of columns of the data.frame.

NROW and NCOL are nice because they tend to give "expected" results for most objects. I use them a lot interactively, but fall back to nrow, ncol, and length when writing stable code (e.g. programs, packages) because they avoid the overhead of a few extra function calls.

like image 58
Joshua Ulrich Avatar answered Sep 21 '22 06:09

Joshua Ulrich