我在R中有一个循环,该循环会根据某些条件获取POSIXct列的先前值。但是,新列不再是POSIXct格式,而是转换为数字。如何避免这种情况?
# 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