1

I want a function is_named_list(lst) which returns true if all elements in the list have a name, and false otherwise. In the case where the list is empty, it should return false. What considerations do I need to account for while trying to write such a function. For example, a list with no names behaves differently to a list with incomplete names, with respect to the names function:

> tmp_list <- list(a = 1, b = 2, 3)
> names(tmp_list)
[1] "a" "b" "" # empty string for unnamed third element

> tmp_list <- list(1, 2, 3)
> names(tmp_list)
NULL # null value when no elements have names.
1

3 Answers 3

3

Just compare the length of the list (length(tmp_list)) against the length of the names vector for that list (length(names(tmp_list))), where the names are not empty string.

all_names <- function(list) {
    return(length(list) == sum(names(list) != "", na.rm=TRUE))
}

> all_names(tmp_list)
[1] FALSE
Sign up to request clarification or add additional context in comments.

Comments

0

We can try

is_named_list <- function(lst) {
    !(is.null(names(lst))|any(!nzchar(names(lst))))
 }
is_named_list(tmp_list) 
#[1] FALSE

and for the second example

tmp_list <- list(1, 2, 3)
is_named_list(tmp_list)
#[1] FALSE

Comments

0
is_named_list <- function(lst) {
    all(names(tmp_list) != "") & !is.null(names(tmp_list))
}

tmp_list <- list(a = 1, b = 2, 3)
is_named_list(tmp_list)
#FALSE
tmp_list <- list(1, 2, 3)
is_named_list(tmp_list)
#FALSE
tmp_list <- list(a = 1, b = 2, c = 3)
is_named_list(tmp_list)
#TRUE

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.