Home > database >  Why does for-loop code break after first iteration?
Why does for-loop code break after first iteration?

Time:10-19

Nums <- c(1:30)

for (i in 1:30) {
  if (Nums[i] %% 2 == 0 & Nums[i] %% 3 != 0) {
    Nums[i] <- c("ok")
  }
}

Nums

I am an Window 10, R 4.1.2 user. I want to replace vectors in Nums with "ok" but results are like this...

Error in Nums[i]%%2 : non-numeric argument to binary operator
> Nums
 [1] "1"  "ok" "3"  "4"  "5"  "6"  "7"  "8"  "9"  "10"
[11] "11" "12" "13" "14" "15" "16" "17" "18" "19" "20"
[21] "21" "22" "23" "24" "25" "26" "27" "28" "29" "30"

Why does for code operate only once?

CodePudding user response:

You can get your desired result without using the for loop:

Nums[Nums %% 2 == 0 & Nums %% 3 != 0] <- "OK"
  • Related