0

I have a large dataframe in R with close to one million rows and 91 columns. For one particular column, I need to replace all negative values with "the value + 360".

All 0 or positive values should remain unchanged.

There are many solutions for setting negative values to 0, or to NA, but I can't quite get this working.

Below are examples of my attempts, with dataframe called df and feature called Bearing.

df$Bearing = apply(df$Bearing, 2, function(x){x[x<0] = x[x+360]})

df$Bearing[df$Bearing <0] <- df%Bearing +360

What is the best way to achieve my aim?

1
  • 2
    You can try ifelse Commented Jun 1, 2018 at 23:16

3 Answers 3

1

Try:

df$Bearing[df$Bearing <0] <- df$Bearing[df$Bearing <0] +360
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, Luke. I think there's a slight typo in your solution (% instead of $) but that's an elegant and simple solution that worked well for me, much appreciated.
Well spotted! Fixed above
0

I would use

df <- within(df, Bearing <- Bearing + ifelse(Bearing < 0, 360, 0))

Comments

0

If speed is an issue because of the size of your data.frame, consider using data.table.

library(data.table)
setDT(df)
df[, bearing := ifelse(bearing < 0, bearing + 360, bearing)]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.