How to count rows?
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 appreciat开发者_StackOverflowe it...
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.
lengths(mylist)
will return the length of each element in the list. Note "lengths" (plural)
int q = list.Length;
int f = list.GetLength(0);
int e = list.GetLength(1);
Console.WriteLine("length of row :" + f);
Console.WriteLine("length of column :" + e);
Console.WriteLine("length of components in list :" + q);
The overall no of components or the length of elements in an array can be found as indicated for variable 'q'. To find the no of rows in a array or list use the function GetLength() with 0 as input value and for no of rows we can use the same function with the intake value as 1.
精彩评论