Search code examples
rposixct

Changing date column if condition is met in another column


I have a large dataset with metadata from images. For some cameras the date was set wrong which i am trying to correct. It seemed pretty straightforward but i can not figure out how to do it without breaking up the dataset. The code below shows essentially what i am trying to do, however, i want to adjust the value inside the complete dataframe without making a subset.

library(lubridate)
data <- data.frame(camera= c("1", "1", "2", "2"),
                   date = c("2000-1-02 01:02:03", "2000-1-02 01:02:03","2000-2-02 01:02:03","2000-2-02 01:02:03"))

data$date <- as.POSIXct(data$date)

camera1 <- subset(data, camera== "1")

camera1$date <- camera1$date - months(1)

I tried to use the dplyr package and the 'if' function to make it work but it seems like the POSIXct format makes things a little more complicated. Preferably i would make the same time adjustment for multiple cameras at the same time.


Solution

  • Suppose you've got several cameras, each with it's own offset from the right time; Camera 1 is a month fast, camera 3 is a month slow.

    data %>% 
      mutate(date = 
               case_when(camera == 1 ~ date - months(1),
                         camera == 3 ~ date + months(1),
                         TRUE ~ date))
    
      camera                date
    1      1 1999-12-02 01:02:03
    2      1 1999-12-02 01:02:03
    3      2 2000-02-02 01:02:03
    4      2 2000-02-02 01:02:03