0

I'm attempting to add a value (360) to all values within a dataframe column that are below 0. I assumed a simple statement would do. However, all this does is change the values to 360, not add the number to the existing value. I feel the solution is really simple but cant work out what it is. Thanks in advance.

##Example data
ID  <- c(1,2,3,4)
val <- c(-180,-150,170,-180)
df <- data.frame (ID,val)   

##My attempt
df$val[df$val < 0] <- + 360

2 Answers2

1

You need subset the data from both the sides.

df$val[df$val < 0] <- df$val[df$val < 0] + 360
df

#  ID val
#1  1 180
#2  2 210
#3  3 170
#4  4 180

Using ifelse might be cleaner and easier to understand.

df$val <- df$val + ifelse(df$val < 0 , 360, 0)
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
1

When using data.table this can be achieved by doing:

df[val < 0, val := val + 360]

or if you use dplyr instead:

df %>%
  mutate(val = ifelse(val < 0, val + 360, val))
koolmees
  • 2,725
  • 9
  • 23