0

I have a dataset called old_images

One of the columns in this dataset is called difference, which can take values between 1 and 1115.

I also have another column called Quarter, which I want to have values of 1, 2, 3, or 4 depending on what Quarter the difference value of that row is.

So the rules would be as follows:

If old_images$difference is between 1 and 279, then old_images$Quarter = 1

ELSE

If old_images$difference is between 280 and 558, then old_images$Quarter = 2

ELSE

If old_images$difference is between 559 and 837, then old_images$Quarter = 3

ELSE

If old_images$difference is between 838 and 1115, then old_images$Quarter = 4

Any help would be hugely appreciated, thank you very much!

EdinPC
  • 23
  • 2
  • 3
  • 9
  • 1
    `dplyr::case_when` will be a good option to use in this case. – MKR Apr 29 '18 at 19:34
  • @user20650: the question you linked to is not about `ifelse` which OP didn't ask for – Tung Apr 29 '18 at 19:36
  • @Tung; agreed, but it provides the same result but in a more efficient way, which seems appropraite – user20650 Apr 29 '18 at 19:37
  • 1
    @EdinPC: see this [answer](https://stackoverflow.com/a/50090097/786542) for `case_when` syntax – Tung Apr 29 '18 at 19:38
  • @user20650: So it's not a exact duplicate then? `ifelse` is not only used for case like this thus it's good for OP to learn a proper way to use it – Tung Apr 29 '18 at 19:43
  • @Tung ; I feel it is correct to direct the op to (one of) the preferred ways to do it, rather than showing the way not to do it - but perhaps I am wrong. Others who disagree can vote to reopen - the beauty of community moderation. (There will be exact duplicates floating about where the same question was asked and likely advised to use `cut` etc. If you can find one I'll add it to the list of duplicate answers. – user20650 Apr 29 '18 at 19:50
  • @Tung, thank you very much for the link. Ended up clicking on your link, which led to another link, then another, then another - ended up with about 20 tabs open haha. Tried a few of the methods, but no joy. However, MKR has provided a solution below that works perfectly. Thank-you for your help though! Very much appreciated. Have a good evening. – EdinPC Apr 29 '18 at 19:57
  • @user20650: can you add this link to the list https://stackoverflow.com/questions/18012222/nested-ifelse-statement EdinPC: you're welcome! – Tung Apr 29 '18 at 20:10

1 Answers1

0

You can using between and case_when from dplyr package as:

 library(dplyr)

  old_images <- old_images %>% mutate(Quarter  = case_when(
  between(difference, 1, 279) ~ 1,
  between(difference, 280, 558) ~ 2,
  between(difference, 559, 837) ~ 3,
  between(difference, 838, 115) ~ 4,
  TRUE                          ~ 4
                        ))
MKR
  • 19,739
  • 4
  • 23
  • 33