0

I have a dataset like this:

        X         Y                A            B           C
1       1        2010              1            1          44
2       1        2010              1            2          17
3       1        2010              1            3           0
4       1        2010              1            4           0
5       1        2010              1            5           0
6       1        2010              1            6           0
...

My aim is to take the values in C that correspond to X==1&Y==2006&A==seq(1,19)&B==19. I thought I should use a While loop making something like this:

for (i in 1:19){
  while (X==1){
    while (Y==2006){
      while (B==19){
        x[i]<-A[i]
      }
    }
  }
}

Nonetheless, the code above doesn't work and there are always warnings() like "the condition has length > 1 and only the first element will be used" Can anyone help?

Carles
  • 2,731
  • 14
  • 25
  • Can you post a [MWE](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) including your data. I assume that that neither x nor A are vectors but matrices/data.frames... – David Jun 10 '20 at 08:08
  • Is your question to return those values in column C where the X, Y, A and B match your conditions? If so, you do not need a loop in R and you can use the inherent vectorisation of many functions. If your dataset is `data` it could look like this: `data[data$X == 1 & data$Y == 2006 & data$A %in% 1:19 & data$B == 19, "C"]`. This is basic sub-setting in R. But I may misunderstand what you are after. – Paul van Oppen Jun 10 '20 at 08:17
  • 2
    Do you need `subset(df, X==1 & Y==2006 & A %in% 1:19 & B==19)` ? – Ronak Shah Jun 10 '20 at 08:18
  • One of ther great strengths of R is that it works on *columns* not *values*. That means that, generally, speaking, if you're considering using a for loop, then there is generally a better (= quicker, shorter) solution.+1 to @RonakShah's suggestion. – Limey Jun 10 '20 at 08:22
  • yeah @RonakShah u got it! Thank u very much – user13719084 Jun 10 '20 at 08:23

0 Answers0