使用 as.POSIXct 在r中转换时间时,会将所有值转换为NA。这是我要做的代码:
data1 %>%
mutate(time_clean = ymd_hms(timestamp,tz = 'UTC')) %>%
separate(time_clean, c('date', 'time'), sep = ' ') %>%
mutate_at(vars(date), funs(as.Date))
数据样本
data1 <- tribble(
~"time", ~"date",
"07:41:47", "2018-11-08",
"07:41:47", "2018-11-08",
"07:41:47", "2018-11-08",
"07:41:50", "2018-11-08",
"07:41:50", "2018-11-08",
"07:41:50", "2018-11-08")
答案 0 :(得分:0)
如果您愿意使用tidyverse
解决方案,这将满足您的要求:
library("tidyverse")
# create example data
example_df <- tibble(time = c("07:41:47", "07:41:47", "07:41:50"),
date = as.Date(c("2018-11-08", "2018-11-08", "2018-11-08")))
example_df %>%
unite(col = "datetime",
c("date", "time"), sep = " ") %>%
mutate(datetime = lubridate::ymd_hms(datetime))
但是,简而言之,您遇到的问题与as.POSIXct
不能只有日期的时间而没有日期的事实有关。因此,您需要将日期和时间放在相同的字符串中,然后进行解析。
相反,如果您专门查找没有日期的“一天中的时间”,则可能要检查this other question on SO