Changing negative values to positive when reading in a CSV

Hi all,

In my df I have a longitude column in which all values must be negative. As I read in my data I make a few adjustments to the df using the read_csv() call and I pipe(%>%) a few checks/modifications to it. I would like to check that all values are negative in a column I created and if they're positive to multiply them by -1 else keep them as is by the following:

df <- ifelse(BestLong > 0, BestLong * -1, BestLong)

But I get this error: Error in ifelse(., BestLong > 0, BestLong * -1, BestLong) : unused argument (BestLong)

I'm not sure why because right before I make this call I've called on the sister columnBestLat without getting an error. This is the full read_csv call that I make when attempting to bring in a tidier data set:

sightings <- read_csv('OM_SightingsData.csv', na = c("", "NA", "<Null>")) %>%
  drop_na(Time1) %>% 
  mutate(SightDateTime = mdy_hms(paste(SightDate, Time1), tz = "US/Pacific"),
         BestLat = coalesce(ActLat, Lat), 
         BestLong = coalesce(ActLong, Long)) %>%
  # Drop sightings with no location data
  mutate_at(vars(BestLat, BestLong), na_if, y = 0) %>%
    drop_na(BestLat) %>% 
    ifelse(BestLong > 0, BestLong * -1, BestLong)
View(sightings)

The code above works perfectly without the ifelse call and I'm not sure why. Any help would be greatly appreciated!

Thank you in advance :slight_smile:

sightings <- read_csv('OM_SightingsData.csv', na = c("", "NA", "<Null>")) %>%
  drop_na(Time1) %>% 
  mutate(SightDateTime = mdy_hms(paste(SightDate, Time1), tz = "US/Pacific"),
         BestLat = coalesce(ActLat, Lat), 
         BestLong = coalesce(ActLong, Long)) %>%
  # Drop sightings with no location data
  mutate_at(vars(BestLat, BestLong), na_if, y = 0) %>%
    drop_na(BestLat) %>% 
    mutate(BestLong = if_else(BestLong > 0, BestLong * -1, BestLong))
View(sightings)

The statement can be included within a mutate function as above to apply the if else statement to that particular column. Right now, you're referencing the column name without passing the data frame along.

Additionally, for safer ifelse statements, use dplyr::if_else(). The rules are a bit more rigorous, so I implore you to look at the function's help page.

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.

@brody_smith Thank you! I wasn't aware that dplyr had an if_else function. I am reading through it's documentation now, and definitely won't forget this for future issues! Thank you for your time!!

1 Like