How to Subset Lists in R?
Last Updated :
19 Dec, 2021
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
list1= list (1,2,3,4,5)
print (list1)
print (list1[[1]])
print (list1[[2]])
print (list1[[3]])
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
list1= list (1,2,3,4,5)
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
data= list (a= c (1:3),b= c (5:8), "geeks" )
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
data= list (a= c (1:3),b= c (5:8), "geeks" )
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
data= list (a= c (1:3),b= c (5:8), "geeks" )
print (data$a)
print (data$b)
|
Output:
[1] 1 2 3
[1] 5 6 7 8
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...