Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R: Count number of objects in list [closed]

Tags:

list

r

count

Can someone recommend a function that can allow me to count and return the number of items in a list?

library(stringr)  l <- strsplit(words, "a")  if(# number of items in list l < 1)    next 
like image 247
Karl Avatar asked Nov 16 '09 06:11

Karl


People also ask

How do I find the length of a list in R?

To get length of list in R programming, call length() function and pass the list as argument to length function. The length function returns an integer representing the number of items in the list.

How do I count the number of occurrences in a column in R?

To count occurrences between columns, simply use both names, and it provides the frequency between the values of each column. This process produces a dataset of all those comparisons that can be used for further processing.

How do I count the number of observations in a group in R?

count() lets you quickly count the unique values of one or more variables: df %>% count(a, b) is roughly equivalent to df %>% group_by(a, b) %>% summarise(n = n()) .


2 Answers

length(x)

Get or set the length of vectors (including lists) and factors, and of any other R object for which a method has been defined.

lengths(x)

Get the length of each element of a list or atomic vector (is.atomic) as an integer or numeric vector.

like image 146
Joey Avatar answered Sep 24 '22 04:09

Joey


Advice for R newcomers like me : beware, the following is a list of a single object :

> mylist <- list (1:10) > length (mylist) [1] 1 

In such a case you are not looking for the length of the list, but of its first element :

> length (mylist[[1]]) [1] 10 

This is a "true" list :

> mylist <- list(1:10, rnorm(25), letters[1:3]) > length (mylist) [1] 3 

Also, it seems that R considers a data.frame as a list :

> df <- data.frame (matrix(0, ncol = 30, nrow = 2)) > typeof (df) [1] "list" 

In such a case you may be interested in ncol() and nrow() rather than length() :

> ncol (df) [1] 30 > nrow (df) [1] 2 

Though length() will also work (but it's a trick when your data.frame has only one column) :

> length (df) [1] 30 > length (df[[1]]) [1] 2 
like image 38
Skippy le Grand Gourou Avatar answered Sep 22 '22 04:09

Skippy le Grand Gourou