Home > database >  How can I change a date style in R?
How can I change a date style in R?

Time:08-13

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:

my dataset looks like this

I want to change the ldr_start column to this: ldr_start 3/92 7/93 8/93

Thank you.

CodePudding user response:

It's not really a "date" in either case. The zoo package does define a yearmon class. Here we can just use strsplit and process the month-character, match against the R Constant, month.abb, and then rejoin:

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"

CodePudding user response:

We could also use stringr's str_replace_all:

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

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

Output:

[1] "3-92" "2-93" "7-94"
  •  Tags:  
  • r
  • Related