Home > database >  Why does for-loop code is only working once in R?
Why does for-loop code is only working once in R?

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 Window10, R 4.1.2 user. I want to replace vectors in Nums with "ok" but results are like this... Why does for code operate only once?

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"

CodePudding user response:

These are vectorized operations and we don't need any for loop here.

replace(Nums, Nums%%2 == 0 & Nums%%3 !=0, "ok")

Once we assign a character value to the numeric, it no longer is numeric type, i.e it converts to character. With the for loop it may be better to store the output in a new vector

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

-output

> Out
 [1] "1"  "ok" "3"  "ok" "5"  "6"  "7"  "ok" "9"  "ok" "11" "12" "13" "ok" "15" "ok" "17" "18" "19" "ok" "21" "ok" "23" "24" "25" "ok" "27" "ok" "29" "30"

CodePudding user response:

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

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