2.4 C
London
Friday, December 20, 2024
HomeStatistics TutorialRHow to Append Values to a Vector Using a Loop in R

How to Append Values to a Vector Using a Loop in R

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...

To append values to a vector using a loop in R, you can use the following basic syntax:

for(i in 1:10) {
  data 

The following examples show how to use this syntax in practice.

Example 1: Append Values to Empty Vector

The following code shows how to append values to an empty vector in R:

#define empty vector
data 

#use for loop to add integers from 1 to 10 to vector 
for(i in 1:10) {
  data #view resulting vector
data

[1]  1  2  3  4  5  6  7  8  9 10

Example 2: Perform Operation & Append Values to Vector

The following code shows how to perform an operation and append values to an empty vector:

#define empty vector
data 

#use for loop to add square root of integers from 1 to 10 to vector 
for(i in 1:10) {
  data sqrt(i))
}

#view resulting vector
data
[1] 1.000000 1.414214 1.732051 2.000000 2.236068 2.449490 2.645751 2.828427
[9] 3.000000 3.162278

Example 3: Append Values to Existing Vector

The following code shows how to append values to an existing vector in R:

#define vector of data
data #define new data to add
new 
#use for loop to append new data to vector
for(i in 1:length(new)) {
  data #view resulting vector
data

[1] 4 5 12 16 16 17 18

Example 4: Append a Single Value to Vector

If you simply want to append a single value to the end of an existing vector, you can use the following code without a for loop:

#define vector of data
data #append the value "19" to the end of the vector
new #display resulting vector
new

[1] 4 5 12 19

You can find more R tutorials on this page.

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