15.1 C
London
Friday, July 5, 2024
HomeStatistics TutorialRHow to Subset Lists in R (With Examples)

How to Subset Lists in R (With Examples)

Related stories

Learn About Opening an Automobile Repair Shop in India

Starting a car repair shop is quite a good...

Unlocking the Power: Embracing the Benefits of Tax-Free Investing

  Unlocking the Power: Embracing the Benefits of Tax-Free Investing For...

Income Splitting in Canada for 2023

  Income Splitting in Canada for 2023 The federal government’s expanded...

Can I Deduct Home Office Expenses on my Tax Return 2023?

Can I Deduct Home Office Expenses on my Tax...

Canadian Tax – Personal Tax Deadline 2022

  Canadian Tax – Personal Tax Deadline 2022 Resources and Tools...

You can use the following syntax to subset lists in R:

#extract first list item
my_list[[1]]

#extract first and third list item
my_list[c(1, 3)]

#extract third element from the first item
my_list[[c(1, 3)]] 

The following examples show how to this syntax with the following list:

#create list
my_list hey")

#view list
my_list

$a
[1] 1 2 3

$b
[1] 7

$c
[1] "hey"

Example 1: Extract One List Item

The following code shows various ways to extract one list item:

#extract first list item using index value
my_list[[1]]

[1] 1 2 3

#extract first list item using name
my_list[["a"]]

[1] 1 2 3

#extract first list item using name with $ operator
my_list$a

[1] 1 2 3

Notice that all three methods lead to the same result.

Example 2: Extract Multiple List Items

The following code shows various ways to extract multiple list items:

#extract first and third list item using index values
my_list[c(1, 3)]

$a
[1] 1 2 3

$c
[1] "hey"

#extract first and third list item using names
my_list[c("a", "c")]

$a [1] 1 2 3

$c [1] "hey"

Both methods lead to the same result.

Example 3: Extract Specific Element from List Item

The following code shows various ways to extract a specific element from a list item:

#extract third element from the first item using index values
my_list[[c(1, 3)]] 

[1] 3

#extract third element from the first item using double brackets
my_list[[1]][[3]]

[1] 3

Both methods lead to the same result.

Additional Resources

How to Convert a List to a Data Frame in R
How to Append Values to List in R

Subscribe

- Never miss a story with notifications

- Gain full access to our premium content

- Browse free from up to 5 devices at once

Latest stories