R 将海军日落/日出数据转换为时间

R 将海军日落/日出数据转换为时间,r,time,timestamp,datetime-conversion,R,Time,Timestamp,Datetime Conversion,我已经从海军下载了2015-2017年日落/日出数据,我正在尝试将其格式化为日期和时间,以便进一步与我拥有的其他数据一起使用。这就是我的数据集在R中的外观 我已设法将日期转换为正确的R数据格式。但是,我仍然无法将上升/设置列数据从数字/整数格式转换为时间数据hh:mm。 基于一个互联网来源,我编写了以下代码: Sun2015$Srise<- format(strptime(Sun2015$Rise, format="%H:%M")) 然而,这在我的数据中给出了NA 或 然而,我收到了

我已经从海军下载了2015-2017年日落/日出数据,我正在尝试将其格式化为日期和时间,以便进一步与我拥有的其他数据一起使用。这就是我的数据集在R中的外观

我已设法将日期转换为正确的R数据格式。但是,我仍然无法将上升/设置列数据从数字/整数格式转换为时间数据hh:mm。 基于一个互联网来源,我编写了以下代码:

Sun2015$Srise<- format(strptime(Sun2015$Rise, format="%H:%M")) 
然而,这在我的数据中给出了NA

然而,我收到了以下错误:

警告消息:In.parse_hms…,order=HM,quiet=quiet: 某些字符串无法分析

是否有更好的方法将列转换为正确的时间格式,以便我可以将日期和时间列合并为日落和日出的日期时间列?
提前感谢您的帮助

您可以使用sprint%04d数据将军事时间转换为2400个时间字符串,然后从那里开始。例如,对于数据的前5行:

# Sample of your data
Day <- c("1/1/2015", "1/2/2015", "1/3/2015", "1/4/2015", "1/5/2015")
Rise <- c(652,652,652,653,653)
Set <- c(1755,1756,1756,1757,1757)

sun2015 <- data.frame(Day, Rise, Set)

# Convert to 2400 style strings with leading zeroes where necessary
sun2015$Rise <- sprintf("%04d", sun2015$Rise)
sun2015$Set <- sprintf("%04d", sun2015$Set)

# Merge with your date
sun2015$day_rise <- as.POSIXct(paste0(sun2015$Day, " ",sun2015$Rise), format = "%m/%d/%Y %H%M", origin = "1970-01-01", tz = "UTC")
sun2015$day_set <- as.POSIXct(paste0(sun2015$Day, " ",sun2015$Set), format = "%m/%d/%Y %H%M", origin = "1970-01-01", tz = "UTC")

> sun2015$day_rise
[1] "2015-01-01 06:52:00 UTC" "2015-01-02 06:52:00 UTC" "2015-01-03 06:52:00 UTC" "2015-01-04 06:53:00 UTC"
[5] "2015-01-05 06:53:00 UTC"
> sun2015$day_set
[1] "2015-01-01 17:55:00 UTC" "2015-01-02 17:56:00 UTC" "2015-01-03 17:56:00 UTC" "2015-01-04 17:57:00 UTC"
[5] "2015-01-05 17:57:00 UTC"

如有必要,您可以调整到适当的时区

谢谢,我能把时间转换成2400格式。不幸的是,最后一个结合日出和日落的时间和日期的代码没有工作。它告诉我你可以用dput命令共享你的数据结构。例如,dputsun2015将提供代码来重新创建整个数据集。您只需使用dputheadsun2015[1:5]即可共享最上面的几行,然后我们可以直接在您的数据上运行代码以找出错误的来源。2015数据Sun2015dputSun2015 dputheadsun2015如果您在R控制台中运行dputheadsun2015[1:5],则输出将是可以生成相同数据结构的代码。你应该在你的帖子里分享。
# Sample of your data
Day <- c("1/1/2015", "1/2/2015", "1/3/2015", "1/4/2015", "1/5/2015")
Rise <- c(652,652,652,653,653)
Set <- c(1755,1756,1756,1757,1757)

sun2015 <- data.frame(Day, Rise, Set)

# Convert to 2400 style strings with leading zeroes where necessary
sun2015$Rise <- sprintf("%04d", sun2015$Rise)
sun2015$Set <- sprintf("%04d", sun2015$Set)

# Merge with your date
sun2015$day_rise <- as.POSIXct(paste0(sun2015$Day, " ",sun2015$Rise), format = "%m/%d/%Y %H%M", origin = "1970-01-01", tz = "UTC")
sun2015$day_set <- as.POSIXct(paste0(sun2015$Day, " ",sun2015$Set), format = "%m/%d/%Y %H%M", origin = "1970-01-01", tz = "UTC")

> sun2015$day_rise
[1] "2015-01-01 06:52:00 UTC" "2015-01-02 06:52:00 UTC" "2015-01-03 06:52:00 UTC" "2015-01-04 06:53:00 UTC"
[5] "2015-01-05 06:53:00 UTC"
> sun2015$day_set
[1] "2015-01-01 17:55:00 UTC" "2015-01-02 17:56:00 UTC" "2015-01-03 17:56:00 UTC" "2015-01-04 17:57:00 UTC"
[5] "2015-01-05 17:57:00 UTC"