0

I am trying to write a for loop and if statement that correct a column. This is the code I tried to do. If time is not NA and CA = 0 then CA = 1. If time is NA and CA = 0 then CA = 0. Else CA = 2

Data dfz:

Time CA FO
200 0 0
1000 0 0
500 0 0
800 0 0
1200 0 0
1300 0 0
1800 0 0
1500 0 0
NA 0 0
NA 0 0
NA 0 0

This is the code I have tried but keep getting all 2 or 0:

for (x in dfz$Time) {
  for(y in dfz$CA){
    if(!(is.na(x)) & y == 0){
      dfz$CA = 1
      }else if ((is.na(x)) & y == 0){
        dfz$CA = 0
        }else{
          dfz$CA = dfz$CA
        }
    }
}
Jan
  • 2,245
  • 1
  • 2
  • 16
  • 1
    What language is this? – Dai Jul 17 '23 at 17:33
  • Please edit your question and add a tag for the language you're using – devlin carnate Jul 17 '23 at 17:34
  • This is in R language – Tierra Smith Jul 17 '23 at 18:24
  • Could you edit your question to include sample data and your desired outcome? – jpsmith Jul 17 '23 at 18:31
  • It's easier to help you if you include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output that can be used to test and verify possible solutions. Please [do not post code or data in images](https://meta.stackoverflow.com/q/285551/2372064) – MrFlick Jul 17 '23 at 19:25

1 Answers1

0

The problem is that in the loop over the first value of x you alter every y since you also loop over y. Thus, from the second x loop on you don't alter the y from the original data frame.

Instead, you can replace the for loop with the vectorised ifelse().

dfz <- data.frame(
    Time = c(200, 1000, 500, 800, 1200, 1300, 1800, 1500, NA, NA, NA),
    CA = 0,
    FO = 0
)

dfz$CA = ifelse(!(is.na(dfz$Time) & dfz$CA == 0), 1,
                ifelse(is.na(dfz$Time) & dfz$CA == 0, 0, dfz$CA))

> dfz
   Time CA FO
1   200  1  0
2  1000  1  0
3   500  1  0
4   800  1  0
5  1200  1  0
6  1300  1  0
7  1800  1  0
8  1500  1  0
9    NA  0  0
10   NA  0  0
11   NA  0  0
Jan
  • 2,245
  • 1
  • 2
  • 16