15.1 C
London
Friday, July 5, 2024
HomeStatistics TutorialRHow to Append Values to List in R (With Examples)

How to Append Values to 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 append a single value to a list in R:

#get length of list called my_list
len 

#append value of 12 to end of list
my_list[[len+1]] 

And you can use the following syntax to append multiple values to a list in R:

#get length of list called my_list
len #define values to append to list
new #append values to list
i = 1
while(i 

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

Example 1: Append a Single Value to a List

Suppose we have the following list in R:

#create list
my_list #view list
my_list

[[1]]
[1] 7

[[2]]
[1] 14

[[3]]
[1] 1 2 3

We can use the following syntax to append the value 12 to the end of the list:

#get length of list
len #append value to end of list
my_list[[len+1]] #view list
my_list

[[1]]
[1] 7

[[2]]
[1] 14

[[3]]
[1] 1 2 3

[[4]]
[1] 12

Example 2: Append Multiple Values to a List

Suppose we have the following list in R:

#create list
my_list #view list
my_list

[[1]]
[1] 7

[[2]]
[1] 14

[[3]]
[1] 1 2 3

We can use the following syntax to append several values to the end of the list:

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

[[1]]
[1] 7

[[2]]
[1] 14

[[3]]
[1] 1 2 3

[[4]]
[1] 3

[[5]]
[1] 5

[[6]]
[1] 12

[[7]]
[1] 14

Additional Resources

How to Append Values to a Vector in R
How to Append Rows to a Data Frame 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