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"?
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).
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.
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.
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"
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
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