Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extract the first item in a list(even if the list is empty)

Tags:

r

In R, I want to extract the first item from a nested list of lists; however sometimes the list might be empty.

e.g.:

myList <- list(
            list(ID = 1, Sales = 1000, Product = "Car"),
            list(ID = 2, Sales = 2000, Product = "Boat"),
            list(ID = 3, Sales = 1500, Product = "Bike")
)
myList2 <- list()

So when I make the following call:

myList[[1]]
myList2[[1]]

The first call returns a valid sub-list (ID=1, Sales=1000, Product = "Car") but the second call returns an error -

Error in myList2[[1]] : subscript out of bounds

Is there a simple call I can make that says "return item 1 when the list is populated, otherwise return NULL and do not throw an error"?

like image 652
Brisbane Pom Avatar asked Feb 02 '18 07:02

Brisbane Pom


People also ask

How do you extract the first value from a list?

To extract only first element from a list, we can use sapply function and access the first element with double square brackets. For example, if we have a list called LIST that contains 5 elements each containing 20 elements then the first sub-element can be extracted by using the command sapply(LIST,"[[",1).

How do you extract the first element of a list in Python?

In Python lists are zero-indexed, so the first element is available at index 0 . Similarly, we can also use the slicing syntax [:1] to get the first element of a list in Python.

How do you remove items from the front of a list in Python?

Del operator has similar working as pop() method to remove the elements from the lists in python. The del operator removes the element from the list at a specified index location but does not return the removed item, unlike the pop() method.


2 Answers

We can create a function to return NULL if the length is 0 or else to return the subset of the list

f1 <- function(lst, ind){
   if(length(lst) >=1) lst[[ind]] else NULL
}

f1(myList2, 1)
#NULL

f1(myList, 1)
#$ID
#[1] 1

#$Sales
#[1] 1000

#$Product
#[1] "Car"
like image 97
akrun Avatar answered Sep 28 '22 18:09

akrun


You can use the first function of dplyr package:

first(myList, default = NULL)
first(myList2, default = NULL)

More info on that function here: https://dplyr.tidyverse.org/reference/nth.html

like image 26
Willem Avatar answered Sep 28 '22 17:09

Willem