Extract Non Null Elements from a List in R

Extract non null elements from a list in R

Here's another option:

Filter(Negate(is.null), x)

Extracting non-null elements from a list of list of data.frames in R

We could use nested lapply

lapply(G, function(x) unlist(lapply(x, `[[`, 'dint'), use.names = FALSE))

#$A
#[1] 1 2 3

#$B
#[1] 1 2 3 4 5 6

and similar for "SD" as well

lapply(G, function(x) unlist(lapply(x, `[[`, 'SD'), use.names = FALSE))

#$A
#[1] 0 1 2

#$B
#[1] 2 3 4 5 3 4

R: removing NULL elements from a list

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

Get the first non-null value from selected cells in a row

One option with dplyr could be:

df %>%
rowwise() %>%
mutate(liv6 = with(rle(c_across(liv:liv5)), values[which.max(values != 0)]))

MD liv liv2 liv3 liv4 liv5 liv6
<dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1 100 0 6 1 1 0 6
2 200 0 2 1 0 2 2
3 300 1 0 1 0 7 1
4 400 3 4 1 3 9 3
5 500 4 5 1 5 10 4

Extract non null elements from a list in R

Here's another option:

Filter(Negate(is.null), x)

How to extract non-empty values from each column of a dataframe and make a list?

You can use pivot_longer with values_drop_na = T:

library(tidyverse)
df %>%
na_if("") %>%
pivot_longer(-Date, values_drop_na = T, names_to = "Company", values_to = "Number")

Date Company Number
<date> <chr> <chr>
1 2020-06-25 B 3
2 2020-06-25 C 3
3 2020-06-26 A 2
4 2020-06-26 C 2
5 2020-06-27 A 1

You can also use pivot_longer and handle empty cells with filter:

df %>% 
pivot_longer(-Date, names_to = "Company", values_to = "Number") %>%
filter(Number != "")

How to filter out NULL elements of tibble's list column

One possibility also involving purrr could be:

df %>%
filter(!map_lgl(var2, is.null))

id var1 var2
<int> <chr> <list>
1 4 B <tibble [4 × 2]>

Reflecting the properties of is.null(), you can also do:

df %>%
rowwise() %>%
filter(!is.null(var2))


Related Topics



Leave a reply



Submit