Open In App

How to Subset Lists in R?

Last Updated : 19 Dec, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will discuss how to subset lists in R programming language.

Method 1: Extract One List Item

We can extract using an index number. Indexing starts with 1 

Syntax:

list[[index_number]]

where, list is the input list

Example: Subset List

R




# create list of elements
list1=list(1,2,3,4,5)
  
# display
print(list1)
  
# get 1 st element
print(list1[[1]])
  
# get 2 nd element
print(list1[[2]])
  
# get 3 rd element
print(list1[[3]])
  
# get 4 th element
print(list1[[4]])


Output:

[[1]]
[1] 1

[[2]]
[1] 2

[[3]]
[1] 3

[[4]]
[1] 4

[[5]]
[1] 5

[1] 1
[1] 2
[1] 3
[1] 4

Method 2: Extract Multiple List Items

We can also select the items at a time using index numbers with c() function

Syntax:

list

Example: Subset List

R




# create list of elements
list1=list(1,2,3,4,5)
  
# get 1,2,3 element
print(list1[c(1, 2,3)])


Output:

[[1]]
[1] 1

[[2]]
[1] 2

[[3]]
[1] 3

Method 3: Extract Multiple List Items with slice operator

Here we are going to use index numbers in slice operator.

Syntax:

list

where,

  • list is the input list
  • index_start is the start position in the list
  • index_end id the end position in the list

Example: Subset List

R




# create list
data=list(a=c(1:3),b=c(5:8),"geeks")
  
# get elements from 1 to 3
print(data[c(1:3)])


Output:

Method 4: Using sapply() function

Here we can access the elements from the sapply() using index numbers

Syntax:

sapply(list,"[",c(index))

Example: Subset List

R




# create list
data=list(a=c(1:3),b=c(5:8),"geeks")
  
# get elements of index 1 and 2
sapply(data,"[",c(1,2))


Output:

Method 5: Using $ operator

Here we are using $ operator to get the elements using the name.

Syntax:

list$name

Example: Subset List

R




# create list
data=list(a=c(1:3),b=c(5:8),"geeks")
  
# get elements from a
print(data$a)
  
# get elements from b
print(data$b)


Output:

[1] 1 2 3
[1] 5 6 7 8


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads