Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why does my 'for' loop break due to a boolean set-membership check, and how do I fix it?

I am recoding data in R and want a basic for-loop with the following properties:

  • Assess every value in a vector.

  • If the value is not a member of a fixed set, then recode the value to 0.

    MEDevel.com: Open-source for Healthcare and Education

    Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

    Visit Medevel

For the following example code, that would mean that all 50 values in the array ‘data’ are assessed and will be recoded to 0, 1, 3, or 5. However, the loop stops early and only the first few numbers are recoded.

set = c(1, 3, 5)

data<-round(runif(n=50, min=1, max=8), 0)
data #initial data set

for (x in data) {
  if (!(data[x] %in% set)) {
    data[x]<- 0
  }
}

data #recoded data

My troubleshooting: I tried to insert an else..next statement to keep the loop going.

>Solution :

The correct for loop is:

Use the indices of data. In your actual for loop you are using the values:

for (i in seq_along(data)) {
  if (!(data[i] %in% set)) {
    data[i] <- 0
  }
}

#data
#recoded data
 [1] 1 0 0 0 3 0 0 0 0 5 3 0 3 3 0 0 0 1 0 0 5 0 0 0 0 0 5 0 0 0
[31] 0 0 5 0 3 1 0 5 0 1 0 1 3 0 0 0 5 0 3 0
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading