简体   繁体   English

as.POSIXct 将时间更改为 NA

[英]as.POSIXct changing time to NA

When converting time in r using as.POSIXct converts all the values to NA.使用as.POSIXct在 r 中转换时间时,会将所有值转换为 NA。 This is my code to do it:这是我的代码:

data1 %>%
mutate(time_clean = ymd_hms(timestamp,tz = 'UTC')) %>%
separate(time_clean, c('date', 'time'), sep = ' ') %>%
mutate_at(vars(date), funs(as.Date))

Sample of the data数据样本

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")

If you're open to tidyverse solutions, this will accomplish what you need:如果您愿意接受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))

But in brief, the issue you're having is related to the fact that as.POSIXct cannot have only a time of the date, without the date.但简而言之,您遇到的问题与as.POSIXct不能只有日期时间而没有日期这一事实有关。 So you need to put date and time in the same string, and then parse it.所以你需要把日期和时间放在同一个字符串中,然后解析它。

If instead you are specifically looking into "time of the day" without date, you may want to check this other question on SO相反,如果您正在专门查看没有日期的“一天中的时间”,您可能需要在 SO 上查看其他问题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM