Open In App

How to add Key Value Pair to List in R ?

Improve
Improve
Like Article
Like
Save
Share
Report

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())
 
# create key value variables
key1 <- "Age"
value1 <- 21
 
key2 <- "Name"
value2 <- "Pulkit"
 
# create the list
mylist <- list()
 
# Build up key value pairs
mylist[[ key1 ]] <- value1
mylist[[ key2 ]] <- value2
 
# Access value using the key
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())
 
# Creating the list
mylist<-list("Name"="Pulkit","Age"=21,
             "Gender"="Male")
 
# Access value using the key
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())
 
# initialize keys and respected values
students <- c("Pulkit", "Ritika", "Parth",
              "Vishesh", "Dharvik", "krishav",
              "Reshav")
 
marks <- c(75, 92, 97, 80, 85, 87, 52)
 
# make the list
results <- setNames(as.list(marks), students)
 
# Access value using the key
print(results$Pulkit)


Output:

 75


Last Updated : 01 Oct, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads