关于日期时间:如何更改 R 中的日期值? | 珊瑚贝

How to change date value in R?


我有这个数据框,我只在 R 中导入了时间,它自动添加了日期,格式如下:

1
2
3
4
 horidat$CORD4
 [1]”1899-12-31 06:25:00 UTC””1899-12-31 06:45:00 UTC””1899-12-31 07:00:00 UTC””1899-12-31 07:15:00 UTC”
 [5]”1899-12-31 07:30:00 UTC””1899-12-31 07:45:00 UTC””1899-12-31 07:57:00 UTC””1899-12-31 08:09:00 UTC”
 [9]”1899-12-31 08:21:00 UTC””1899-12-31 08:32:00 UTC””1899-12-31 08:43:00 UTC””1899-12-31 08:54:00 UTC”

我只想将日期 1899-12-31 更改为不同的日期,例如 2010-01-25。它们采用 POSIXct 格式。

如果可能的话,你能告诉我怎么做吗?

  • 看看这个帖子stackoverflow.com/questions/42397196/…


这样就可以了(在 base R 中)

1
2
3
4
5
6
7
8
9
10
paste(‘2010-01-25’, format(as.POSIXct(horidat$CORD4), ‘%T’))
# [1]”2010-01-25 06:25:00″”2010-01-25 06:45:00″

# or with (local) time zone
paste(‘2010-01-25’, format(as.POSIXct(horidat$CORD4), ‘%T %Z’)) # or %z for digits
# [1]”2010-01-25 06:25:00 CET””2010-01-25 06:45:00 CET” # (I’m in a different time zone)

# or keeping the class POSIXct
as.POSIXct(paste(‘2010-01-25’, format(as.POSIXct(horidat$CORD4), ‘%T’)))
# [1]”2010-01-25 06:25:00 CET””2010-01-25 06:45:00 CET”

与数据

1
2
horidat <- data.frame(CORD4 = c(‘1899-12-31 06:25:00 UTC’,’1899-12-31 06:45:00 UTC’),
                      stringsAsFactors = FALSE)
  • 嗨,纳特,非常感谢!第一部分似乎正在工作。但我认为我不理解这部分是日期的最后一部分,这只会使 horidat 成为具有两个值的数据框,对吗?如何将过去应用于日期框架?
  • @Hanna 最后一部分(horidat <- …)只是其他用户能够重现代码的示例。 (由于您已经有了数据 horidat,请忽略第二部分)
  • 抱歉,我还有一个问题,你知道我怎样才能保持 POSIXct 格式吗?这样做后它假定字符格式,我的想法是在此转换后计算与其他数据帧和列的时间差。谢谢你。
  • @Hanna 只需使用 as.POSIXct – 请参阅我在答案中的编辑(方法 3)。


来源:https://www.codenong.com/54306897/

微信公众号
手机浏览(小程序)

Warning: get_headers(): SSL operation failed with code 1. OpenSSL Error messages: error:14090086:SSL routines:ssl3_get_server_certificate:certificate verify failed in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57

Warning: get_headers(): Failed to enable crypto in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57

Warning: get_headers(https://static.shanhubei.com/qrcode/qrcode_viewid_9478.jpg): failed to open stream: operation failed in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57
0
分享到:
没有账号? 忘记密码?