0

I have a loop in R that gets the previous value of a POSIXct column based on some conditions. However, the new column is not in POSIXct format anymore but is instead converted to numeric. How can I avoid this?

# Set up dataframe
df <- data.frame(
  building = c('a','a','a','a','b','b','b'),
  hour = c(as.POSIXct(c('2019-01-01 15:00:00','2019-01-01 15:00:00','2019-01-01 17:00:00','2019-01-01 18:00:00',
                        '2019-01-01 15:00:00','2019-01-01 16:00:00','2019-01-01 17:00:00')))
)

#Loop to get previous value of 'hour' based on conditions
df$prev_hour <- NA
for (i in 2:nrow(df)){
  if(df$building[i]==df$building[i-1] & as.integer(df$hour[i]-df$hour[i-1])<2){
    df$prev_hour[i] <- as.POSIXct(df$hour[i-1])
  }
}

df
  building                hour  prev_hour
        a  2019-01-01 15:00:00         NA
        a  2019-01-01 15:00:00 1546372800
        a  2019-01-01 17:00:00         NA
        a  2019-01-01 18:00:00 1546380000
        b  2019-01-01 15:00:00         NA
        b  2019-01-01 16:00:00 1546372800
        b  2019-01-01 17:00:00 1546376400
Gaurav Bansal
  • 5,221
  • 14
  • 45
  • 91
  • 2
    Try this instead to initialize the column: `df$prev_hour <- as.POSIXct(NA)`. (Which is kinda weird, and I sometimes wish there was an `NA_posix_` value or something. – joran Jun 28 '19 at 20:45
  • 1
    The reason you're getting an error is because the column ```df$prev_hour``` is not being read as POSIXct, so that's why you need to convert it as joran mentioned. – Jacky Jun 28 '19 at 20:48

0 Answers0