[英]How to retain month/year from the day/month/year date format using R
There is an excel file containing dates in the form day/month/year. 有一个excel文件,其中包含日/月/年表格中的日期。 I want to retain the month and the year in the form month/year using R. 我希望使用R保留月/年的月份和年份。
I have tried by making use of the function "format" as below: 我尝试过使用“格式”功能,如下所示:
date = c("2/8/2018","22/11/2018","1/2/2019")
n.date <- format(as.Date(date), "%m/%Y")
It gives: 它给:
n.date
[1] "08/0002" "11/0022" "02/0001"
However, I expect to have something like 但是,我希望有类似的东西
"8/2018" "11/2018" "2/2019".
Please, how do I go about this. 拜托,我该怎么做呢。 Any help is greatly appreciated. 任何帮助是极大的赞赏。
You should be using the format
option in your call to as.Date
, when you parse the strings into dates, with the mask %d/%m/%Y
. 当您使用掩码%d/%m/%Y
将字符串解析为日期时,您应该在调用as.Date
时使用format
选项。 Then, call format()
with the month-year mask you want: 然后,使用您想要的月 - 年掩码调用format()
:
date = c("2/8/2018", "22/11/2018", "1/2/2019")
n.date <- as.Date(date, format="%d/%m/%Y")
format(n.date, "%m/%Y")
[1] "08/2018" "11/2018" "02/2019"
To remove the leading zeroes: 要删除前导零:
output <- format(n.date, "%m/%Y")
output <- sub("^0*", "", output)
output
[1] "8/2018" "11/2018" "2/2019"
If you check as.Date(date)
it doesn't give you correct dates. 如果你检查as.Date(date)
它没有给你正确的日期。 So usually the answer by @Tim is the way to go however, you can also use regex to achieve your desired result here 所以通常@Tim的答案是可行的方法,你也可以使用正则表达式来实现你想要的结果
sub("\\d+/", "", date)
#[1] "8/2018" "11/2018" "2/2019"
This deletes a number followed by "/" in date
. 这将删除date
后跟“/”的数字。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.