gpt4 book ai didi

r - 在R中更改日期格式

转载 作者:行者123 更新时间:2023-12-03 12:01:33 25 4
gpt4 key购买 nike

我在R中有一些非常简单的数据,需要更改其日期格式:

 date midpoint
1 31/08/2011 0.8378
2 31/07/2011 0.8457
3 30/06/2011 0.8147
4 31/05/2011 0.7970
5 30/04/2011 0.7877
6 31/03/2011 0.7411
7 28/02/2011 0.7624
8 31/01/2011 0.7665
9 31/12/2010 0.7500
10 30/11/2010 0.7734
11 31/10/2010 0.7511
12 30/09/2010 0.7263
13 31/08/2010 0.7158
14 31/07/2010 0.7110
15 30/06/2010 0.6921
16 31/05/2010 0.7005
17 30/04/2010 0.7113
18 31/03/2010 0.7027
19 28/02/2010 0.6973
20 31/01/2010 0.7260
21 31/12/2009 0.7154
22 30/11/2009 0.7287
23 31/10/2009 0.7375

我希望使用 %d/%m/%Y的标准R格式,而不是 %Y-%m-%d
我该如何进行更改?我试过了:
nzd$date <- format(as.Date(nzd$date), "%Y/%m/%d")

但这只是截止年份,并在当天增加了零:
 [1] "0031/08/20" "0031/07/20" "0030/06/20" "0031/05/20" "0030/04/20"
[6] "0031/03/20" "0028/02/20" "0031/01/20" "0031/12/20" "0030/11/20"
[11] "0031/10/20" "0030/09/20" "0031/08/20" "0031/07/20" "0030/06/20"
[16] "0031/05/20" "0030/04/20" "0031/03/20" "0028/02/20" "0031/01/20"
[21] "0031/12/20" "0030/11/20" "0031/10/20" "0030/09/20" "0031/08/20"
[26] "0031/07/20" "0030/06/20" "0031/05/20" "0030/04/20" "0031/03/20"
[31] "0028/02/20" "0031/01/20" "0031/12/20" "0030/11/20" "0031/10/20"
[36] "0030/09/20" "0031/08/20" "0031/07/20" "0030/06/20" "0031/05/20"

谢谢!

最佳答案

这里有两个步骤:

  • 解析数据。您的示例不是完全可复制的,文件中的数据还是文本或因子变量中的变量?让我们假设后者,那么如果您将data.frame称为X,则可以执行

  •  X$newdate <- strptime(as.character(X$date), "%d/%m/%Y")


    现在 newdate列应为 Date类型。
  • 格式化数据。只需调用format()strftime()即可:

  •  format(X$newdate, "%Y-%m-%d")


    一个更完整的示例:
    R> nzd <- data.frame(date=c("31/08/2011", "31/07/2011", "30/06/2011"), 
    + mid=c(0.8378,0.8457,0.8147))
    R> nzd
    date mid
    1 31/08/2011 0.8378
    2 31/07/2011 0.8457
    3 30/06/2011 0.8147
    R> nzd$newdate <- strptime(as.character(nzd$date), "%d/%m/%Y")
    R> nzd$txtdate <- format(nzd$newdate, "%Y-%m-%d")
    R> nzd
    date mid newdate txtdate
    1 31/08/2011 0.8378 2011-08-31 2011-08-31
    2 31/07/2011 0.8457 2011-07-31 2011-07-31
    3 30/06/2011 0.8147 2011-06-30 2011-06-30
    R>

    第三和第四列之间的区别在于类型: newdateDate类,而 txtdate是字符。

    关于r - 在R中更改日期格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7439977/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com