我正在尝试按照另一篇 StackOverflow 帖子中的说明进行操作,因为我有类似的问题:我需要将时间戳转换为事件发生后的天数(或小时)。
我的问题是,当我尝试将时间戳转换为日期时,我不断收到此错误:
Error in assign(cacheKey, frame, .rs.CachedDataEnv) : attempt to use zero-length variable name
据说这意味着我在代码中包含分隔符,但我不确定这在此特定数据集的上下文中意味着什么或如何解决它。
这应该是一个可重现的示例:
sample <- c(1,2,3,4,5)
timestamp <- c('2023-07-17-15-05','2023-07-17-16-05','2023-07-17-17-05','2023-07-18-15-05','2023-07-17-19-05')
area <- c(255,345,200,177,189)
df <- data.frame(sample,timestamp,area)
df$timestamp <- as.Date(df$timestamp,format='%Y-%m-%d_%h-%m')
时间戳布局是年-月-日-时-分,如果有帮助的话。
无论代码中是否有破折号或斜杠,都会发生这种情况。我不确定该下划线是否是分隔小时和分钟的正确方法,但如果我使用它仍然会引发相同的错误:
sample <- c(1,2,3,4,5)
timestamp <- c('2023-07-17-15-05','2023-07-17-16-05','2023-07-17-17-05','2023-07-18-15-05','2023-07-17-19-05')
area <- c(255,345,200,177,189)
df <- data.frame(sample,timestamp,area)
df$timestamp <- as.Date(df$timestamp,format='%Y-%m-%d-%h-%m')
我尝试用谷歌搜索错误,但找不到任何对我来说有意义的解释,说明这个特定时间戳发生了什么或任何指向修复的内容。
提前致谢!
在最后的注释中使用
timestamp
,如果您尝试将其转换为没有小时和分钟的日期,那么
as.Date(timestamp) # as.Date ignores junk at end
## [1] "2023-07-17" "2023-07-17" "2023-07-17" "2023-07-18" "2023-07-17"
as.Date(timestamp, "%Y-%m-%d") # only need year, month & day in format
## [1] "2023-07-17" "2023-07-17" "2023-07-17" "2023-07-18" "2023-07-17"
as.Date(timestamp, "%F") # same as %Y-%m-%d
## [1] "2023-07-17" "2023-07-17" "2023-07-17" "2023-07-18" "2023-07-17"
或者如果您想保留小时和分钟,请确保格式与输入相对应。输入在日期后面有一个 -,而不是下划线,所以这有效:
as.POSIXct(timestamp, format = "%Y-%m-%d-%H-%M")
## [1] "2023-07-17 15:05:00 EDT" "2023-07-17 16:05:00 EDT"
## [3] "2023-07-17 17:05:00 EDT" "2023-07-18 15:05:00 EDT"
## [5] "2023-07-17 19:05:00 EDT"
as.POSIXct(timestamp, format = "%F-%H-%M") # same
## [1] "2023-07-17 15:05:00 EDT" "2023-07-17 16:05:00 EDT"
## [3] "2023-07-17 17:05:00 EDT" "2023-07-18 15:05:00 EDT"
## [5] "2023-07-17 19:05:00 EDT"
lubridate:::ymd_hm(timestamp)
## [1] "2023-07-17 15:05:00 UTC" "2023-07-17 16:05:00 UTC"
## [3] "2023-07-17 17:05:00 UTC" "2023-07-18 15:05:00 UTC"
## [5] "2023-07-17 19:05:00 UTC"
timestamp <- c('2023-07-17-15-05','2023-07-17-16-05',
'2023-07-17-17-05','2023-07-18-15-05','2023-07-17-19-05')