R: removing NULL elements from a list

remove empty elements from list r
r remove na from list
remove element from list r
removing an item from a list in r
remove first element of a list r
r remove row from list
remove character from list in r
removing items from a list r
mylist <- list(NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, 
    123, NULL, 456)

> mylist
[[1]]
NULL

[[2]]
NULL

[[3]]
NULL

[[4]]
NULL

[[5]]
NULL

[[6]]
NULL

[[7]]
NULL

[[8]]
NULL

[[9]]
NULL

[[10]]
NULL

[[11]]
[1] 123

[[12]]
NULL

[[13]]
[1] 456

My list has 13 elements, 11 of which are NULL. I would like to remove them, but preserve the indices of the elements that are nonempty.

mylist2 = mylist[-which(sapply(mylist, is.null))]
> mylist2
[[1]]
[1] 123

[[2]]
[1] 456

This removes the NULL elements just fine, but I don't want the nonempty elements to be reindexed, i.e, I want mylist2 to look something like this, where the indices of the nonempty entries are preserved.

> mylist2
[[11]]
[1] 123

[[13]]
[1] 456

The closest you'll be able to get is to first name the list elements and then remove the NULLs.

names(x) <- seq_along(x)

## Using some higher-order convenience functions
Filter(Negate(is.null), x)
# $`11`
# [1] 123
# 
# $`13`
# [1] 456

# Or, using a slightly more standard R idiom
x[sapply(x, is.null)] <- NULL
x
# $`11`
# [1] 123
# 
# $`13`
# [1] 456

How to clear the R environment - General, How do I remove the null elements from a list of lists, like below, in R: if the function is to also remove objects like list(NULL) (not the same as NULL ), as is​.null)) ## Recursively step down into list, removing all such objects  As you can see based on Figure 2, we just removed the second list element of our example list. In order to delete this list component, we just needed to write a square bracket, a minus sign, and the positioning of the list element we wanted to delete (i.e. [- 2]) behind the name of our list.

There's a function that automatically removes all the null entries of a list, and if the list is named, it maintains the names of the non-null entries.

This function is called compact from the package plyr.

l <- list( NULL, NULL, foo, bar)
names(l) <- c( "one", "two", "three", "four" )

plyr::compact(l)

If you want to preserve the indexes of the non-null entries, you can name the list as it is done in the post before and then compact your list:

names(l) <- seq_along(l)
plyr::compact(l)

R is.null Function, If you have a list with NULL elements, the following will remove them: A[!sapply(A​, is.null)] A is the list. Functions referenced: sapply null list  This function removes all elements evaluated to be TRUE by an indicator function. The removal can be recursive so that the resulted list surely does not include such elements in any level. The removal can be recursive so that the resulted list surely does not include such elements in any level.

Simply do mylist[lengths(mylist) != 0].

R List - Learn what all you can do with Lists in R!, Sometimes, not only NULL values are undesired, empty vectors or lists are also fun = function(x) length(x) == 0L can be useful to remove all empty elements of​  Funny enough, none of the many solutions above remove the empty/blank character string: "".But the trivial solution is not easily found: L[L != ""]. To summarize, here are some various ways to remove unwanted items from an array list.

If you want to keep the names you can do

a <- list(NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, 
          123, NULL, 456)
non_null_names <- which(!sapply(a, is.null))
a <- a[non_null_names]
names(a) <- non_null_names
a

You can then access the elements like so

a[['11']]
num <- 11
a[[as.character(num)]]
a[[as.character(11)]]
a$`11`

You can't get them in the neat [[11]], [[13]] notation, though, because those represent numerical indices.

Remove NULL elements from list of lists, Remove NULL Values. Removes all NULL elements from a list or vector. Keywords: misc  Remove Objects from a Specified Environment. remove and rm can be used to remove objects. These can be specified successively as character strings, or in the character vector list, or through a combination of both. All objects thus specified will be removed. If envir is NULL then the currently active environment is searched first.

The purrr package, included in Tidyverse, has elegant and fast functions for working with lists:

require(tidyverse)

# this works
compact(mylist)

# or this
mylist %>% discard(is.null)

# or this
# pipe "my_list" data object into function "keep()", make lambda function inside "keep()" to return TRUE FALSE.
mylist %>% keep( ~ !is.null(.) )

All above options are from Purrr. Output is:

[[1]] 
[1] 123

[[2]] 
[1] 456

Note: compact() was in plyr, but dplyr superseded plyr, and compact() stayed around but moved to purrr. Anyway, all the functions are within the parent package tidyverse.

Here's a link to the Purrr cheat sheet download:

https://rstudio.com/resources/cheatsheets/

Or to view the Purrr cheatsheet directly in a browser:

https://evoldyn.gitlab.io/evomics-2018/ref-sheets/R_purrr.pdf

Remove NULL elements from a list in R, [R] removing NULL elements from a list. Carlos Ortega carlos.ortega at minorplanet.com. Mon Apr 14 17:14:48 CEST 2003. Previous message: [R] removing  The Java Collections Framework offers a simple solution for removing all null elements in the List – a basic while loop: @Test public void givenListContainsNulls_whenRemovingNullsWithPlainJava_thenCorrect() { List<Integer> list = Lists.newArrayList(null, 1, null); while (list.remove(null)); assertThat(list, hasSize(1)); }

list.clean function, HI, I have the list: > suu [[1]] NULL [[2]] NULL [[3]] item_id prod 1 2 [[4]] item_id prod 1 2 2 4 how to delete all "NULL" elements from suu to get  list.remove(.data, range = integer()) Arguments.data A list or vector range A numeric vector of indices or a character vector of names to remove from .data. Aliases.

delete.NULLs function, Drop rows with missing values in R is done in multiple ways like using na.omit() and complete.cases() function drop rows with null in R. Drop NA NaN values. And the relevant section of the R FAQ says: Do not set x[i] or x[[i]] to NULL, because this will remove the corresponding component from the list. Which seems to tell you (in a somewhat backwards way) how to remove an element. Hope that helps, or at least leads you in the right direction.

[R] removing NULL elements from a list, Queue, Quizzes, R Language, Randomized, Reasoning – Placements, Recursion, Ruby Python | Pandas Reverse split strings into two List/Columns using str.rsplit() More concise and better approach to remove all the empty strings, it just trailing empty elements from given list · Python - Remove empty List from List  Much like many other objects that you will encounter in R, lists aren’t static objects. You can change components, add components, and remove components from them in a pretty straightforward manner. Changing the value of components Assigning a new value to a component in a list is pretty straightforward. You use either the $ or …

Comments
  • Someone may find a way, but I think you are falling into the "Why is it printing that way" trap. Those index numbers are not the names of your list elements. There are no names. Check names(mylist). So they are just helpers showing where in the list the elements are. That's why you're having trouble telling R to return the 11th position of a list with only two elements. You can try naming the the list as the answer below.
  • IMO this answer should be updated to @Hayward-Oblad's purrr solution below. Either list %>% discard(is.null) or list %>% discard(~ length(.x) == 0).
  • For completeness: purrr::compact() seems to do the same job.
  • @naive Yes, but function lengths() was introduced in R 3.2.0, i.e. only 3.5y ago.
  • Users stuck with even older R versions can use vapply(mylist, length, 1L), it's ever-so-slightly vaster (and maybe harder to read to the untrained eye)
  • This is the closest to what you want that can actually be done though :)
  • Filter(Negate(is.null), setNames(L,seq_along(L))) is pretty easy to read.
  • Ok, fixed the issue. Negate != !