13.2 C
London
Tuesday, July 2, 2024
HomeStatistics TutorialRHow to Create an Empty List in R (With Examples)

How to Create an Empty List in R (With Examples)

Related stories

Learn About Opening an Automobile Repair Shop in India

Starting a car repair shop is quite a good...

Unlocking the Power: Embracing the Benefits of Tax-Free Investing

  Unlocking the Power: Embracing the Benefits of Tax-Free Investing For...

Income Splitting in Canada for 2023

  Income Splitting in Canada for 2023 The federal government’s expanded...

Can I Deduct Home Office Expenses on my Tax Return 2023?

Can I Deduct Home Office Expenses on my Tax...

Canadian Tax – Personal Tax Deadline 2022

  Canadian Tax – Personal Tax Deadline 2022 Resources and Tools...

You can use the following syntax to create an empty list in R:

#create empty list with length of zero
empty_list 

#create empty list of length 10
empty_list list', length=10)

The following examples show how to use these functions in practice.

Example 1: Create Empty List in R with Length of Zero

The following code shows how to create an empty list with a length of zero in R:

#create empty list
empty_list #verify that empty_list is of class 'list'
class(empty_list)

[1] "list"

#view length of list
length(empty_list)

[1] 0

The result is a list with a length of 0.

Example 2: Create Empty List in R with Specific Length

The following code shows how to create an empty list of length 8 in R:

#create empty list of length 8
empty_list list', length=8)

#verify that empty_list is of class 'list'
class(empty_list)

[1] "list"

#view list
empty_list
[[1]]
NULL

[[2]]
NULL

[[3]]
NULL

[[4]]
NULL

[[5]]
NULL

[[6]]
NULL

[[7]]
NULL

[[8]]
NULL

The result is a list with a length of 8 in which every element in the list is NULL.

Example 3: Append Values to Empty List in R

One of the most common reasons to create an empty list is to then fill it with values using a loop.

The following code shows how to create an empty list, then fill it with values:

#create empty list of length 8
empty_list list', length=8)

#get length of list
len #define values to append to list
new #fill values in list
i = 1
while(i #display updated list
empty_list

[[1]]
[1] 3

[[2]]
[1] 5

[[3]]
[1] 12

[[4]]
[1] 14

[[5]]
[1] 17

[[6]]
[1] 18

[[7]]
[1] 18

[[8]]
[1] 20

Notice that the empty list is now filled with the new values that we specified.

Additional Resources

How to Create an Empty Data Frame in R
How to Append Values to List in R
How to Convert List to Vector in R

Subscribe

- Never miss a story with notifications

- Gain full access to our premium content

- Browse free from up to 5 devices at once

Latest stories