9.5 C
London
Sunday, March 9, 2025
HomeStatistics TutorialRFor-Loop with Range in R (Including Examples)

For-Loop with Range in R (Including 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 basic syntax to write a for-loop with a range in R:

for(i in 1:10) {
  do something
}

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

Example 1: Print Values in Range

The following code shows how to use a for-loop to print every value in a certain range:

#print every value in range of 1 to 10
for(i in 1:10) {
  print(i)
}

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

Example 2: Perform Operation on Values in Range

The following code shows how to use a for-loop to perform a specific operation on every value in a certain range:

#define vector
x 

#print square root of every value in vector
for(i in 1:length(x)) {
 print(paste('The square root of the value in position', i, 'is', sqrt(x[i])))
}

[1] "The square root of the value in position 1 is 2"
[1] "The square root of the value in position 2 is 2.64575131106459"
[1] "The square root of the value in position 3 is 3"
[1] "The square root of the value in position 4 is 3.46410161513775"
[1] "The square root of the value in position 5 is 3.74165738677394"
[1] "The square root of the value in position 6 is 4"
[1] "The square root of the value in position 7 is 4.35889894354067"

Example 3: Perform Operation on Values in Data Frame

The following code shows how to use a for-loop to perform a specific operation on every value in a specific column of a data frame in r:

#define data frame
df frame(a=c(3, 4, 4, 5, 8),
                 b=c(8, 8, 7, 8, 12),
                 c=c(11, 15, 19, 15, 11))

#view data frame
df

  a  b  c
1 3  8 11
2 4  8 15
3 4  7 19
4 5  8 15
5 8 12 11

#multiply every value in column 'a' by 2
for(i in 1:length(df$a)) {
  df$a[i] = df$a[i]*2
}

#view updated data frame
df

   a  b  c
1  6  8 11
2  8  8 15
3  8  7 19
4 10  8 15
5 16 12 11

Additional Resources

How to Create a Nested For Loop in R
How to Write a Nested If Else Statement in R
How to Loop Through Column Names 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