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...
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With