我想将这些日期转换为这种格式"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")
但它只是把还给我
[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
我被卡住了!
最后一个选项可以修改为包括当天的%d
,当我们在当天为paste
时。此外,在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"