我有一些来自事件制作者的数据。在“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
关于r - 转换时间不适用于列的数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67622390/