r语言 - 转换时间不适用于列的数据帧



我有一些来自事件生成器的数据。在一个";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)

我的价值观仍然存在问题。

这里有什么提示吗?

我建议进行以下小的更改。。。

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

有两件事对我有用:

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,to=10)
col2<-rep("1613488656",10)
df <- data.frame(cbind(col1,col2))
colnames(df)<-c("index","created_at")

df$created_at <- convert_time(df$created_at)

两者都发出警告,但似乎正确地进行了校正

最新更新