在 R 中转换日期
Converting date in R
我想将这些日期转换为“1995-01”、“1995-02”等格式
这是我的一些数据
Date Change
1 January-1995 0.01417476
2 February-1995 0.01427050
3 March-1995 0.01556348
4 April-1995 0.01644737
5 May-1995 0.01603727
6 June-1995 0.01627500
7 July-1995 0.01557800
8 August-1995 0.01429773
9 September-1995 0.01344300
10 October-1995 0.01334667
11 November-1995 0.01328429
12 December-1995 0.01345368
13 January-1996 0.01293091
14 February-1996 0.01301762
15 March-1996 0.01289048
16 April-1996 0.01268476
17 May-1996 0.01287364
18 June-1996 0.01253400
19 July-1996 0.01254591
20 August-1996 0.01271238
21 September-1996 0.01245700
22 October-1996 0.01201636
23 November-1996 0.01191300
24 December-1996 0.01195600
我试过了:
date <- as.Date(Data$Date,format="%B/%Y")
还有这个
date <- as.Date(paste0("01/", Data$Date),format = "%m/%Y")
但它只是return我
[1] NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA
我卡住了!
最后一个选项可以修改为在我们 paste
当天包含 %d
日期。此外,在 format
中指定正确的分隔符和 %B
-(完整的月份名称),其中 %m
- 月份为十进制数)
as.Date(paste0("01/", Data$Date),format = "%d/%B-%Y")
或使用lubridate
library(lubridate)
my(Data$Date)
my("January-1995")
[1] "1995-01-01"
这是另一个基本 R 选项,但输出类型为 string
(不是 Date
)
x <- c("January-1995", "February-1996")
paste0(
gsub("\D", "", x),
"-",
sprintf("%02d", match(gsub("-.*", "", x), month.name))
)
这给出了
[1] "1995-01" "1996-02"
我想将这些日期转换为“1995-01”、“1995-02”等格式
这是我的一些数据
Date Change
1 January-1995 0.01417476
2 February-1995 0.01427050
3 March-1995 0.01556348
4 April-1995 0.01644737
5 May-1995 0.01603727
6 June-1995 0.01627500
7 July-1995 0.01557800
8 August-1995 0.01429773
9 September-1995 0.01344300
10 October-1995 0.01334667
11 November-1995 0.01328429
12 December-1995 0.01345368
13 January-1996 0.01293091
14 February-1996 0.01301762
15 March-1996 0.01289048
16 April-1996 0.01268476
17 May-1996 0.01287364
18 June-1996 0.01253400
19 July-1996 0.01254591
20 August-1996 0.01271238
21 September-1996 0.01245700
22 October-1996 0.01201636
23 November-1996 0.01191300
24 December-1996 0.01195600
我试过了:
date <- as.Date(Data$Date,format="%B/%Y")
还有这个
date <- as.Date(paste0("01/", Data$Date),format = "%m/%Y")
但它只是return我
[1] NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA
我卡住了!
最后一个选项可以修改为在我们 paste
当天包含 %d
日期。此外,在 format
中指定正确的分隔符和 %B
-(完整的月份名称),其中 %m
- 月份为十进制数)
as.Date(paste0("01/", Data$Date),format = "%d/%B-%Y")
或使用lubridate
library(lubridate)
my(Data$Date)
my("January-1995")
[1] "1995-01-01"
这是另一个基本 R 选项,但输出类型为 string
(不是 Date
)
x <- c("January-1995", "February-1996")
paste0(
gsub("\D", "", x),
"-",
sprintf("%02d", match(gsub("-.*", "", x), month.name))
)
这给出了
[1] "1995-01" "1996-02"