-2

Element in a numeric vector does not change after running a for loop that iterates each element.

I have a numeric vector:

>str(df$Grad.Rate)
num [1:777] 60 56 54 59 15 55 63 73 80 52 ...

I want to update any element>100

> for (i in df$Grad.Rate){
+     if (i >100){
+         print(i)
+         i = 100
+         print(paste0('changed to ', i))
+     }
+ }
[1] 118
[1] "changed to 100"

After I run the for loop, the element that is >100 is still in the vector

> any(df$Grad.Rate>100)
[1] TRUE

Why?

Sven Hohenstein
  • 80,497
  • 17
  • 145
  • 168
Kelvin Chen
  • 11
  • 1
  • 2
  • You are just `print`ing and not updating the dataset. You may need to loop through the sequence and update it. But, this can be done easily without a loop, `df$Grad.Rate[df$Grad.Rate > 100] <- 100` or `df$Grad_Rate <- pmax(100, df$Grad.Rate)` – akrun Dec 31 '18 at 14:49

2 Answers2

0

Instead of i = 100, you have to use

df$Grad.Rate[i] <- 100

in your loop. You can also choose to change the elements without a loop:

df$Grad.Rate[df$Grad.Rate > 100] <- 100
Sven Hohenstein
  • 80,497
  • 17
  • 145
  • 168
0

We can do this without any loop

df$Grad.Rate[df$Grad.Rate > 100] <- 100

Or

df$Grad_Rate <- pmin(100, df$Grad.Rate) 

In the for loop, the values are not updated. Instead, we can loop through the sequence and update it

for (i in seq_along(df$Grad.Rate)){
 if (df$Grad.Rate[i] >100){

     df$Grad.Rate[i] <- 100

  }
akrun
  • 874,273
  • 37
  • 540
  • 662