[R] list of lists, is this element empty
Ben Tupper
btupper at bigelow.org
Sat Dec 20 17:18:29 CET 2014
Hi,
On Dec 20, 2014, at 10:58 AM, Ragia Ibrahim <ragia11 at hotmail.com> wrote:
> Hello,
> Kindly I have a list of lists as follow
> x
> [[1]]
> [1] 7
>
> [[2]]
> [1] 3 4 5
>
> as showen x[[3]] does not have a value and it has NULL, how can I check on this
> how to test if x[[3]] is empty.
>
In general you can us is.null()
x <- list(7, 3:5, NULL, "A")
> is.null(x[[3]])
[1] TRUE
but be aware that trying access an element by index that is greater than the length of the list will cause you issues.
> is.null(x[[10]])
Error in x[[10]] : subscript out of bounds
You can make your own function to test for the existence of an element and if it is NULL. Note that the function isn't complete in the sense that it doesn't test if you provide an negative index, that x is not a list, etc. You can add all of those tests in.
is_null <- function(x, index){
( index[1] > length(x) ) || is.null(x[[index[1]]])
}
> is_null(x, 1)
[1] FALSE
> is_null(x, 3)
[1] TRUE
> is_null(x, 10)
[1] TRUE
There a lot of info on index at
> ?`[`
Does that answer your question?
Cheers,
Ben
> thanks in advance
> Ragia
>
> [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
Ben Tupper
Bigelow Laboratory for Ocean Sciences
60 Bigelow Drive, P.O. Box 380
East Boothbay, Maine 04544
http://www.bigelow.org
More information about the R-help
mailing list