how to create a list in R Programming with examples

 

How to create list in R

The list can store data of multiple data type. A List can store multiple R objects like different types of atomic vectors such as character, numeric, logical. We can create a list using list() function. We need to pass vector(s) as parameters.

Syntax : list_variable = list( vector 1,vector 2, . . . . , vector n )

We can generate random values using the sample function:

Syntax : sample( vector , size=value , replace=T or F , prob=c(probability values for the vector) )

Note : Here prob is not mandatory to pass . prob refers the probability of values to be repeated .

Example

# creating a list with sample function

lst1 = list(sample(1 : 10, size = 10, replace = F))

 # printing the list variable

print(lst1)

 

Explanation : 

·         In the first step, we have created a list using the sample function for generating random values.

·         In the sample function, we have taken vectors with 1 to 10 values as the first parameter.

·         As the second parameter, we have taken size=10. Since we have taken size=10 it will generate 10 random values from the vector

·         As the third parameter, we have taken replace=F. So, no value will be repeated.

·         Finally, printing the list variable.

Example 2: With replace as TRUE

The main point here to remember is if we want to assign replace=FALSE, size is always less than or equal to vector size, otherwise, execution will be halted.

# creating a list with sample function

lst1 = list(sample(1 : 10, size = 15, replace = T))

 # printing the list variable

print(lst1)

Example 3: With prob attribute 

# creating a list with sample function

lst1 = list(sample(1 : 5, size = 15,

                   replace = T,

                   prob = c(0.02, 0.2, 0.25, 0.5, 0.9)))

 # printing the list variable

print(lst1)

 

Code explanation :

·         In the fourth parameter, we have taken the prob attribute and assigned some probabilities for the vector values. The first value in the prob represents the probability for the first value of the vector. likewise v1=> p1 , v2 => p2. . . . . . vn => pn . Here v represents vector and p represents prob.

·         In the output, we can observe that 1 is not there. Because we have given probability as 0.02 . Due to less probability, it is not generated by the r interpreter. Other than 1 all the values are generated and repeated since they have a greater probability as compared to 1.

 

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.

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)

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

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)

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:

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)

 

Access Index Names of List Using lapply Function in R

 

The lapply() method in R programming language returns a list of the same length as that of the supplied vector, each element of which is obtained as the result of applying FUN to the corresponding element of the vector.

Syntax:

lapply (X, FUN, )

Parameter : 

X – an atomic vector or list to apply the function on

FUN – the function to be applied over each element of X. 

Method 1: Using seq_along()

The seq_along() method in R is used to generate a sequence of elements of a length equivalent to that of the input length of the passed argument. The generated sequence always begins with the integer values starting from 1. 

Syntax:

seq_along (X)

Parameter : 

X – passed argument

The seq_along() generated sequence is passed as the first argument of the function lapply(). The function FUN comprises the concatenation of the names assigned to different components of the list which can be accessed using the index and the list name along with the component vectors or list values appended together using the comma separator. The index names of the specified list can be accessed using the following syntax : 

names (list-obj)[[index-cntr]]

The element values can be accessed using the following syntax : 

list-obj [[index-cntr]]

# declaring and creating a list

lst <- list(ele1 = 1:5,       

                ele2 = c(FALSE,TRUE),

                ele3 = LETTERS[4:9])

 

# printing list contents

print ("List contents : ")

print (lst)

 # accessing elements

print ("Accessing elements : ")

lapply(seq_along(lst),

       function(i) paste(names(lst)[[i]],

                         "->",

                         paste(lst[[i]], collapse = ", ")))

Method 2: Using seq()

The seq() method can also be used to traverse through the list and its components individually. The method works similarly to the seq_along() method. 

seq() function in R is used to create a sequence of elements in a Vector. It takes the length and difference between values as an optional argument. 

Syntax:
seq(from, to, by, length.out)

Parameters:
from: Starting element of the sequence
to: Ending element of the sequence
by: Difference between the elements
length.out: Maximum length of the vector

Example: 

# declaring and creating a list

lst <- list(ele1 = 1:5,       

                ele2 = c(FALSE,TRUE),

                ele3 = LETTERS[4:9])

 # printing list contents

print ("List contents : ")

print (lst)

 # accessing elements

print ("Accessing elements : ")

lapply(seq(lst),

       function(i) paste(names(lst)[[i]], "->",

                         paste(lst[[i]], collapse = ", ")))

 

Count Number of List Elements in R

 

To use length() and lengths() to find the elements count in a list.

Steps –

·         Create a list with vectors/list/range operator

·         Find the count of elements using the length and lengths function.

Syntax: list(value1,value2,…,value)

values can be range operator or vector.

# range from 10 to 50

values = 10:50

  

# vector elements of character type

names = c("sravan", "bobby", "ojaswi", "gnanu")

  # data1 with list of elements

data1 = list(1, 2, 3, 4, 5)

  # give input to the data which is a list

data = list(values, names, data1)

  # display

print(data)

Example 1: Using length() function.

Length function is used to count the elements in the list

Syntax: length(listname)

return value: integer

# range from 10 to 50

values = 10:50

  

# vector elements of character type

names = c("sravan", "bobby", "ojaswi", "gnanu")

  # data1 with list of elements

data1 = list(1, 2, 3, 4, 5)

  # give input to the data which is a list

data = list(values, names, data1)

  # display

print(data)

  # count elements using length function

print(length(data))

Example 2: For finding the length of each data in a list (nested list) we will use lengths() function

Syntax: lengths(list_name)

# range from 10 to 50

values = 10:50

  # vector elements of character type

names = c("sravan", "bobby", "ojaswi", "gnanu")

  # data1 with list of elements

data1 = list(1, 2, 3, 4, 5)

  # give input to the data which is a list

data = list(a1 = values, a2 = names, a3 = data1)

  # display

print(data)

  # count elements in each nested  using lengths function

print(lengths(data))

 

 

Comments

Popular posts from this blog

How to create Animated 3d chart with R.

Linux/Unix Commands frequently used

R Programming Introduction