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.
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With