问题描述
我有一些来自事件生产者的数据。在“created_at 列中,我有混合类型的日期时间值。
一些 NA,一些 ISO8601 之类的,一些 POSIX 有和没有毫秒。
我构建了一个函数,它应该处理一切意味着让我们按原样处理 NA 和 ISO8601 信息,并将 POSIX 日期转换为 ISO8601。
library(anytime)
convert_time <- function(x) {
nb_char = nchar(x)
if (is.na(x)) return(x)
else if (nb_char == 10 | nb_char == 13) {
num_x = as.numeric(x)
if (nb_char == 13) {
num_x = round(num_x / 1000,0)
}
return(anytime(num_x))
}
return(x)
}
如果我传递了一个有问题的值
convert_time("1613488656")
“2021-02-16 15:17:36 UTC”
效果很好!
现在
df_offer2$created_at = df_offer2$created_at %>% sapply(convert_time)
我仍然有有问题的价值观。
这里有什么提示吗?
解决方法
对我有用的两件事:
col1<-seq(from=1,to=10)
col2<-rep("1613488656",10)
df <- data.frame(cbind(col1,col2))
colnames(df)<-c("index","created_at")
df <- df%>%
mutate(converted = convert_time(df$created_at))`
替代
col1<-seq(from=1,"created_at")
df$created_at <- convert_time(df$created_at)
两者都吐出警告,但似乎正确地进行了更正
,我建议进行以下小改动...
convert_time <- function(x) {
nb_char = nchar(x)
if (is.na(x)) return(x)
else if (nb_char == 10 | nb_char == 13) {
num_x = as.numeric(x)
if (nb_char == 13) {
num_x = round(num_x / 1000,0)
}
return(num_x) #remove anytime from here
}
return(x)
}
df_offer2$created_at = df_offer2$created_at %>%
sapply(convert_time) %>% anytime() #put it back in at this point