Mexolini
Mexolini

Reputation: 73

Subtracting or adding to column value based on its value in R

I Have a dataframe named mydata. Here's a sample of the relevant column:

Accuracy.Percentage
100.00
127.00
60.00
175.00
52.00

Now, what I want to accomplish is the following: when the value of a row is < 100, I want change its value with 100 - mydata$Accuracy.Percentage, when the value is > 100, I want to change its value with mydata$Accuracy.Percentage - 100. I have tried something like

result <- if(mydata$Accuracy.Percentage < 100) { 
  mutate(result$Accuracy.Percentage = 100 - result$Accuracy.Percentage) 
  } 
else mutate(result$Accuracy.Percentage = result$Accuracy.Percentage - 100)

But I can't seem to get it to work, although there probably is a simple way to accomplish this. Thanks in advance, I hope I have been clear enough and formulated my question in a understandable manner!

Upvotes: 2

Views: 51

Answers (2)

KL_
KL_

Reputation: 1513

I think abs() will help you, but you need to remember the ifelse statement (ifelse(test, true, false)):

mutate(ifelse(
    mydata$Accuracy.Percentage < 100,
    result$Accuracy.Percentage=100-result$Accuracy.Percentage
    result$Accuracy.Percentage=result$Accuracy.Percentage-100
))

Edited with @nadizan comment

Upvotes: 1

nadizan
nadizan

Reputation: 1373

Maybe try ifelse.

ifelse(
  mydata$Accuracy.Percentage < 100,
  100 - mydata$Accuracy.Percentage,
  mydata$Accuracy.Percentage - 100
)

Upvotes: 1

Related Questions