Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R: Using the unlist() function for a list that has some elements being integer(0)?

Tags:

r

In R, I am calling unlist on a list to convert to a vector. However, some of my list elements are empty, and hence returns integer(0). The unlist() function by default drops this. How can I return a vector that has NA where the list is empty? I have created a reproducible example:

> ex.list <- list()
> ex.list[[1]] <- integer(0)
> ex.list[[2]] <- c(1,2,3)
> ex.list
[[1]]
integer(0)

[[2]]
[1] 1 2 3

> unlist(ex.list)
[1] 1 2 3

Thanks.

like image 478
user321627 Avatar asked Jun 20 '18 04:06

user321627


People also ask

How do I unlist a list in R?

Use unlist() function to convert a list to a vector by unlisting the elements from a list. A list in R contains heterogeneous elements meaning can contain elements of different types whereas a vector in R is a basic data structure containing elements of the same data type.

What is the use of unlist () function?

unlist() function in R Language is used to convert a list to vector. It simplifies to produce a vector by preserving all components. # Creating a list. Here in the above code we have unlisted my_list using unlist() and convert it to a single vector.

What does list () do in R?

The list() function in R is used to create a list of elements of different types. A list can contain numeric, string, or vector elements.

How do you access the elements of a list in R?

A list in R is created with the use of list() function. R allows accessing elements of a list with the use of the index value. In R, the indexing of a list starts with 1 instead of 0 like other programming languages.


1 Answers

A way of doing it is to use function is.na<-.

is.na(ex.list) <- lengths(ex.list) == 0

ex.list
#[[1]]
#[1] NA
#
#[[2]]
#[1] 1 2 3

Then you will have a NA where the list had a length of 0.

unlist(ex.list)
#[1] NA  1  2  3
like image 159
Rui Barradas Avatar answered Nov 28 '22 12:11

Rui Barradas