无法使用 lubridate 合并日期(字符类型)和时间(字符类型),并且创建的新列始终显示 N/As

问题描述 投票:0回答:1

我正在尝试使用 lubridate 将日期(mdy)和时间(hms)合并到我的数据的新列中。我希望新的日期时间列的顺序为 y-m-d h:m:s。

我尝试使用的以下代码是...

sa1$datetime <- ymd_hms(paste(sal$date,sal$time), format = "%Y-%m-%d, %H:%M:%S")

sal1 是我的数据表,其中包含日期列 (myd | example - 7/6/23)、时间 (hms | example - 0:00:00) 和每 15 分钟记录一次的盐度值。但是,当我运行此代码时,出现以下错误...

Error in `$<-.data.frame`(`*tmp*`, datetime, value = c(NA_real_, NA_real_,  : 
  replacement has 2187 rows, data has 2186
In addition: Warning message:
All formats failed to parse. No formats found.

创建新列时,仅显示 N/As,而不显示组合值。我还省略了“sal”数据中的任何 N/As,所以我认为这不应该是一个问题。

sal1 <- sal[-1,]%>%
  na.omit()
date na lubridate
1个回答
0
投票

问题是您的实际数据不是年月日格式,而是日月年,或者可能是月日年格式。因此,您需要使用

ymd_hms()
dmy_hms()
,而不是
mdy_hms()

# create an example dataframe
df <- data.frame(
  date = c("7/6/23", "6/9/69"),
  time = c("0:00:00", "4:20:00"))

dmy_hms(paste(df$date,df$time)) # [1] "2023-06-07 00:00:00 UTC" "1969-09-06 04:20:00 UTC"
© www.soinside.com 2019 - 2024. All rights reserved.