C. Bailey - 5 months ago 24

R Question

I need some help with a for-loop I've been working with. I don't know if what I have done is even possible, but I hope you can help me make it work.

Initially, I have a list of 100 elements, which are all FALSE.

I want to pass through 100 variables to change the elements (FALSE/TRUE).

Step 1 should change every element to TRUE,

Step 2 changes every second element(starting at 2); if FALSE to TRUE and if TRUE to FALSE,

Step 3 changes every third element, and so on.

Here is what I have so far:

`X = rep(FALSE,100)`

for (i in X) {

if (i == X[1]) {

X[X%%1==0] == TRUE

} else {

i = i+1

k = X[X%%i==0]

for (i in k) {

if (k == TRUE) {

replace(X, k, FALSE)

} else {

replace(X, k, TRUE)

}

}

}

}

Finally I want the outcome to sum all the elements that are TRUE, but I don't know how to put that in the loop.

All help is much appreciated!

Answer

```
X = rep(FALSE,100)
for (i in 1:length(X)) {
# Reverse the value of every element,
# then every 2nd starting with 2,
# then every 3rd element starting with 3,
# etc, through every 100th element starting with 100
for(j in 1:100){
if(i %in% seq(j,length(X),j)){
X[i] <- ifelse(X[i]==FALSE,TRUE,FALSE)
}
}
}
```