How to add Key Value Pair to List in R ?
A key-value pair can be explained as a set of two linked data items where a key uniquely identifies a value or a set of values in the data. Since a list can hold multiple data-types data, we can have a key-value pair stored in the list
Method 1:
We can assign variables to each key and value. Store each key-value pair after building the list using square brackets.
R
rm (list = ls ())
key1 <- "Age"
value1 <- 21
key2 <- "Name"
value2 <- "Pulkit"
mylist <- list ()
mylist[[ key1 ]] <- value1
mylist[[ key2 ]] <- value2
print (mylist$Age)
print (mylist$Name)
|
Output:
21
Pulkit
Method 2:
Another way of doing this without using any additional variables is to specify the key and the value in the list() function while creating the list.
Example
R
rm (list = ls ())
mylist<- list ( "Name" = "Pulkit" , "Age" =21,
"Gender" = "Male" )
print (mylist$Age)
print (mylist$Gender)
|
Output:
21
Male
Method 3: Using setNames()
Another approach we can take to add a key-value pair in the list is to setNames() function and inside it, we use as.list(). Basically what we will have here is a syntax like given below, which will create a list and assign all the keys with their respective values.
Syntax:
variable<-setNames(as.list(values), keys)
Example:
R
rm (list = ls ())
students <- c ( "Pulkit" , "Ritika" , "Parth" ,
"Vishesh" , "Dharvik" , "krishav" ,
"Reshav" )
marks <- c (75, 92, 97, 80, 85, 87, 52)
results <- setNames ( as.list (marks), students)
print (results$Pulkit)
|
Output:
75
Last Updated :
01 Oct, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...