2

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!

tyluRp
  • 4,678
  • 2
  • 17
  • 36
Mexolini
  • 41
  • 4

2 Answers2

1

Maybe try ifelse.

ifelse(
  mydata$Accuracy.Percentage < 100,
  100 - mydata$Accuracy.Percentage,
  mydata$Accuracy.Percentage - 100
)
nadizan
  • 1,323
  • 10
  • 23
1

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

KL_
  • 1,503
  • 1
  • 8
  • 13
  • I would suggest you to call `mutate` once and use pipes before the `ifelse` statement, maybe also using `if_else` instead. See here: https://stackoverflow.com/questions/24459752/can-dplyr-package-be-used-for-conditional-mutating – nadizan Mar 20 '18 at 20:44
  • Whoops, I've used his ifelse. Very nice observation! – KL_ Mar 20 '18 at 20:48
  • Thanks a lot! Like you mentioned, in the end abs() was all I needed! – Mexolini Mar 21 '18 at 08:34