【问题标题】:How to change the date format in R如何更改R中的日期格式
【发布时间】:2012-07-30 05:14:41
【问题描述】:

我有一些日期格式如下:

        V1  V2   V3
1 20100420 915   120
2 20100420 920   150
3 20100420 925   270
4 20100420 1530  281

每行3列,第1行表示:2010-04-20 09:15 120

现在我想将其更改为 1 列(时间序列):

                   V3
1 20100420 09:15   120
2 20100420 09:20   150
3 20100420 09:25   270
4 20100420 15:30   281

或:

                   V3
1 20100420 9:15    120
2 20100420 9:20    150
3 20100420 9:25    270
4 20100420 15:30   281

我如何在 R 中实现它?

【问题讨论】:

  • 你试过什么?这在 R 文档和关于 SO 的不同问题中有很好的记录。
  • 澄清一下,在原始数据中,V3是什么?
  • 可能是一些股票的数据,前两列是日期,最后一列可能是open.priceclose.pricevolumn等。
  • V2的格式真的只有三位吗?我假设这代表小时和分钟。一般来说,应该是四位数。时间是 12 小时制还是 24 小时制?如果您希望人们帮助解答,您确实应该提供更清晰的信息。
  • 凌晨 1:00 之前的时间呢?他们只是两位数吗?还是带前导零?您是否以数字或字符的形式阅读这些内容? summary(yourdata) 是怎么说的?

标签: r date format


【解决方案1】:

?strptime?sprintf 是你的朋友:

重新创建数据集:

test <- read.table(textConnection("V1  V2 V3
20100420 915 120
20100420 920 150
20100420 925 270"),header=TRUE)

做一些粘贴:

strptime(
paste(
    test$V1,
    sprintf("%04d", test$V2),
    sep=""
),
format="%Y%m%d%H%M"
)

结果:

[1] "2010-04-20 09:15:00" "2010-04-20 09:20:00" "2010-04-20 09:25:00"

【讨论】:

  • 谢谢,strptime 功能真的很有帮助!我是第一次处理时间序列数据,看起来很复杂。
  • @thelatemail,substr 的所有东西都不是必需的,是吗?只要最终字符串的长度正确,strptime 应该能够很好地解析日期,而不必在字符串中嵌入破折号。
  • @mrdwab - 是的,你是对的。当我不再尝试在手机上打字时,我会将其修复为仅引用 test$V1 而不是子字符串。
【解决方案2】:

首先,修复您的格式并使用像 xts 这样的包来获取正确的时间序列对象:

# Read in the data. In the future, use `dput` or something else
# so that others can read in the data in a more convenient way
temp = read.table(header=TRUE, text=" V1  V2   V3
1 20100420 915   120
2 20100420 920   150
3 20100420 925   270
4 20100420 1530  281")

# Get your date object and format it to a date/time object
date = paste0(temp[[1]], apply(temp[2], 1, function(x) sprintf("%04.f", x)))
date = strptime(date, format="%Y%m%d%H%M")

# Extract just the values
values = temp[[3]]

# Load the xts package and convert your dataset
require(xts)
xts(values, order.by=date)
#                     [,1]
# 2010-04-20 09:15:00  120
# 2010-04-20 09:20:00  150
# 2010-04-20 09:25:00  270
# 2010-04-20 15:30:00  281

在日期转换中:

  • apply(temp[2], 1, ...) 逐行查找 temp 的第二列,并将数字重新格式化为四位数。
  • 然后,paste0 将所有日期时间信息合并到一个向量中。
  • 最后,strptime 将该字符向量转换为适当的日期时间对象。

更新

当然,如果你只想要一个普通的data.frame,你也可以这样做,但如果你想做实时序列分析,我强烈建议使用zooxts

这是简单的data.frame 步骤(在之前创建datevalues 对象之后)。

data.frame(V3 = values, row.names=date)
#                      V3
# 2010-04-20 09:15:00 120
# 2010-04-20 09:20:00 150
# 2010-04-20 09:25:00 270
# 2010-04-20 15:30:00 281

【讨论】:

  • 谢谢!我必须花更多时间在上面。
  • 现在是发布后的“DUH”时刻......简化为一行。对于xtsxts(temp$V3, order.by = strptime(paste0(temp[[1]], sprintf("%04.f", temp[[2]])), format="%Y%m%d%H%M")),对于data.framedata.frame(V3 = temp$V3, row.names = strptime(paste0(temp[[1]], sprintf("%04.f", temp[[2]])), format="%Y%m%d%H%M"))
猜你喜欢
  • 2021-01-11
  • 2019-01-09
  • 1970-01-01
  • 2015-03-03
  • 2011-11-18
  • 1970-01-01
  • 2021-11-28
相关资源
最近更新 更多