0

I am working on mutational data of genes which consists of one column per gene, with the gene either having "no alteration", or a specific mutation. In one column, I want the non-altered genes to be changed to "Wildtype", and all the different mutations to be changed to simply "Mutated". I have tried using the conditional function for this with the following code:

dat$RB <- ifelse(dat$RB != "no alteration", dat$RB == "Mutated RB", dat$RB == "Wildtype RB")

However, when I use this, all values in the column simply change to "FALSE". Why is this not working, and what should I do to achieve my goal?

sao
  • 1,835
  • 6
  • 21
  • 40
  • Does this answer your question? [Conditional replacement of values in a data.frame](https://stackoverflow.com/questions/8214303/conditional-replacement-of-values-in-a-data-frame) – Ian Campbell Jun 08 '20 at 13:26

3 Answers3

1

You can use :

dat$RB <- ifelse(dat$RB == "no alteration", "Wildtype RB", "Mutated RB")

Or without ifelse :

dat$RB <- c("Mutated RB", "Wildtype RB")[(dat$RB == "no alteration") + 1]
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
0

In your question you ask for a solution--see @Ronak's. You also ask for a reason why your code isn't working. Here's an aswer to that.

The syntax of ifelse is threefold: the first argument specifies a condition; the second argument specifies what to do if the conditon holds true, and the third argument specifies what to do if the condition is not met. So if you put ifelse(dat$RB != "no alteration", dat$RB == "Mutated RB", dat$RB == "Wildtype RB") you are making two mistakes: first, you negate the condition that you actually want to match, namely that cells have the value no alternation; to mend that mistake you would need to replace != by ==. Second, I guess dat$RBis a new column; being new and as the ifelse command is being executed not yet extant, you cannot reference the column in the call to ifelse. To mend that mistake you need to specify the values themselves (without reference to the column), namely "Wildcard RB" and "Mutated RB".

Hope this clarifies the issue.

Chris Ruehlemann
  • 20,321
  • 4
  • 12
  • 34
0

We can use case_when from dplyr

library(dplyr)
dat %>%
    mutate(RB = case_when(RB == 'no alteration' ~ 'Wildtype RB', TRUE ~ 'Mutated RB'))
akrun
  • 874,273
  • 37
  • 540
  • 662