简体   繁体   English

如何更改 R 中的日期样式?

[英]How can I change a date style in R?

A column in my dataset includes dates such as Month Name and Year.我的数据集中的一列包括月份名称和年份等日期。 I want to change the month's name to number.我想将月份的名称更改为数字。

My dataset looks like this (but is not limited to only 3 rows):我的数据集如下所示(但不仅限于 3 行):

我的数据集看起来像这样

I want to change the ldr_start column to this: ldr_start 3/92 7/93 8/93我想将 ldr_start 列更改为: ldr_start 3/92 7/93 8/93

Thank you.谢谢你。

It's not really a "date" in either case.无论哪种情况,这都不是真正的“约会”。 The zoo package does define a yearmon class. zoo package 确实定义了一年生 class。 Here we can just use strsplit and process the month-character, match against the R Constant, month.abb , and then rejoin:这里我们可以只使用 strsplit 并处理月份字符,匹配 R 常量, month.abb ,然后重新加入:

dat <- scan(text="Mar-92,Feb-93,Jul-94,Sep-95", what = "", sep=",")
#Read 4 items
datspl <- strsplit(dat, split="-")
sapply( datspl, function(mnyr){ paste( match(mnyr[1], month.abb), mnyr[2], sep="/")})
#[1] "3/92" "2/93" "7/94" "9/95"

We could also use stringr 's str_replace_all :我们也可以使用stringrstr_replace_all

data <- c("Mar-92", "Jul-93", "Aug-93")

str_replace_all(data, setNames(as.character(1:12), month.abb))

Output: Output:

[1] "3-92" "7-93" "8-93"

Using the input defined reproducibly in the Note at the end we have some alternatives.使用最后注释中可重现定义的输入,我们有一些替代方案。

1) yearmmon Using the test data in the Note at the end convert the input column to yearmon class and then format it in the desired fashion. 1) yearmmon使用末尾注释中的测试数据将输入列转换为 yearmon class,然后以所需的方式对其进行格式化。 See?strptime for information on the percent codes.有关百分比代码的信息,请参见 strptime。

library(zoo)

transform(DF, start2 = sub("^0", "", format(as.yearmon(start, "%b-%y"), "%m/%y")))
##    start start2
## 1 Mar-92   3/92

1a) If it is ok to have a leading zero on one digit months then we can omit the sub and just write: 1a)如果可以在一位数月份有前导零,那么我们可以省略sub并只写:

transform(DF, start2 = format(as.yearmon(start, "%b-%y"), "%m/%y"))
##    start start2
## 1 Mar-92  03/92

2) Base R Using only base R we can append 1 to start to make it a valid date (valid dates require year, month and day and not just month and year) and then proceed in a similar way as in (1) or (1a). 2)基础 R仅使用基础 R 我们可以 append 1 start使其成为有效日期(有效日期需要以类似的方式进行) 1a)。

transform(DF, 
  start2 = sub("^0", "", format(as.Date(paste(start, 1),  "%b-%y %d"), "%m/%y")))
##    start start2
## 1 Mar-92   3/92

Note笔记

DF <- data.frame(start = "Mar-92") # test data frame

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM