Extract column from list in R
Last Updated :
26 Mar, 2021
In this article, we are going to create a list of elements and access those columns in R. We are first creating a list with matrix and vectors and access those columns using R.
Approach
Syntax:
list_name=list(var1, var2, varn..)
- Assign names to list elements as columns names. We can give names using names() function
Syntax:
names(list_name)=c(var1, var2, varn)
- Access those columns and elements.
Simple list
Method 1: Using indices
In this method, we simply have to pass the index of the column with the name of the list to extract that specific column.
Example:
R
list1 <- list ( c ( "sravan" , "sudheer" , "vani" , "radha" ),
matrix ( c (98, 87, 78, 87)))
names (list1) <- c ( "names" , "percentage" )
print (list1[1])
print (list1[2])
|
Output:
Method2: Using $ operator.
In this method, the name of the column to be retrieved has to be passed with its name and name of the list separated by the dollar sign($).
Syntax:
list_name$column_name
Example:
R
list1 <- list ( c ( "sravan" , "sudheer" , "vani" , "radha" ),
matrix ( c (98, 87, 78, 87)))
names (list1) <- c ( "names" , "percentage" )
print (list1$names)
print (list1$percentage)
|
Output:
A list with different structures
A list can contain a matrix, vector, and a list as arguments to a list but to access them the method remains the same and it has been discussed in the code below.
Example:
R
list1 <- list ( c ( "sravan" , "sudheer" , "vani" , "radha" ),
matrix ( c (98, 87, 78, 87)),
list ( 'vignan' , 'vit' , 'vvit' , 'rvrjc' ))
names (list1) <- c ( "names" , "percentage" , "college" )
print ( "Method 1" )
print (list1[1])
print (list1[2])
print (list1[3])
print ( "Method 2" )
print (list1$names)
print (list1$percentage)
print (list1$college)
|
Output:
It is possible to access nested elements using [[]] operator.
Syntax:
list_name[[value]][[value]]…
Example:
R
list1 <- list ( c ( "sravan" , "sudheer" , "vani" , "radha" ),
matrix ( c (98, 87, 78, 87)),
list ( 'vignan' , 'vit' , 'vvit' , 'rvrjc' ))
print (list1[[2]][[1]])
print (list1[[2]])
print (list1[[3]][[3]])
|
Output:
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...