这是我正在使用的数据框架。我只包括前六行。我收到的错误信息与这一小部分数据相同。
structure(list(Date.time = c("3/3/22 16:03", "3/4/22 23:41",
"3/14/22 16:32", "3/23/22 11:44", "3/23/22 13:02", "3/23/22 13:14"
)), row.names = c(NA, 6L), class = "data.frame")
我正在使用lubridate
库,我正试图将此列转换为'm/d/y hms'格式(Excel)为R更喜欢的'ymd'格式。
library(lubridate)
我正在尝试创建一个新的变量,它是ymd格式,我指定润滑油正在查看mdy hms。
file$Date.time2 <- lubridate::ymd(file$Date.time, "mdy_hms")
但是,我得到这个错误信息。
All formats failed to parse. No formats found.Error in `$<-.data.frame`(`*tmp*`, Date.time2, value = c(NA_real_, NA_real_, :
replacement has 7 rows, data has 6
我查看这个数据帧的长度,它确实有六行,因为我使用了head()
函数。
length(file$Date.time) # evaluates to 6
我还可以确认这个文件的类是一个数据帧
class(file) # dataframe
数据的全部范围有8077列,润滑告诉我同样的错误信息,说替换有8078行。
我试着用这两种方式运行代码,认为如果我使用一个新的向量而不是原来的向量,错误信息可能会消失。
file$Date.time <- lubridate::ymd(file$Date.time, "mdy_hms")
file$Date.time2 <- lubridate::ymd(file$Date.time, "mdy_hms")
列表的字符串中没有秒,所以您需要使用不包含秒的润滑函数:
library(lubridate)
file <- structure(list(Date.time = c("3/3/22 16:03", "3/4/22 23:41",
"3/14/22 16:32", "3/23/22 11:44", "3/23/22 13:02", "3/23/22 13:14"
)), row.names = c(NA, 6L), class = "data.frame")
file$Date.time2 <- lubridate::mdy_hm(file$Date.time)
下面是一个有用的关于这些函数的备忘单:https://rawgit.com/rstudio/cheatsheets/main/lubridate.pdf