dimanche 28 juillet 2019

Dynamically Change as.POSIXlt Value

In R, I am trying to read a file that has a timestamp, and update the timestamp based on the condition of another field. The below code works with no problem:

t <- data.frame(user = as.character(c("bshelton@email1.com", "lwong@email1.com")), 
                last_update = rep(as.POSIXlt(Sys.time(), tz = "America/Los_Angeles"), 2))
Sys.sleep(5)
t$last_update <- as.POSIXlt(ifelse(t$user == "bshelton@email1.com", Sys.time(), t$last_update), origin = "1970-01-01")  
print(t)

The problem is when I read an existing file and try to dynamically change an as.POSIXlt value. The following code is producing the error that accompanies it in the code block afterwards:

t <- data.frame(user = as.character(c("bshelton@email1.com", "lwong2@email1.com")), 
                last_update = rep(as.POSIXlt(Sys.time(), tz = "America/Los_Angeles"), 2))

write.csv(t, "so_question.csv", row.names = FALSE)
t <- read.csv("so_question.csv")

t$last_update <- as.POSIXlt(t$last_update)
Sys.sleep(5)
t$last_update <- as.POSIXlt(ifelse(t$user == "bshelton@email1.com", Sys.time(), t$last_update), origin = "1970-01-01")  

Error in as.POSIXlt.default(ifelse(t$user == "bshelton@email1.com", Sys.time(),  : 
  do not know how to convert 'ifelse(t$user == "bshelton@email1.com", Sys.time(), t$last_update)' to class “POSIXlt”
In addition: Warning message:
In ans[!test & ok] <- rep(no, length.out = length(ans))[!test &  :
  number of items to replace is not a multiple of replacement length

Aucun commentaire:

Enregistrer un commentaire