Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.9k views
in Technique[技术] by (71.8m points)

dataframe - How to change date format in R data frame and add to new column?

Suppose I have the following data frame with dates from 2020:

date
2020-01-01T05:00:00+0000
2020-02-01T05:00:00+0000
2020-01-01T05:00:00+0000
2020-03-01T05:00:00+0000

The column is of type character.

I want to create a second column which will return.g. Jan-20, Feb-20, etc. I.e. the following:

date                       date_name
2020-01-01T05:00:00+0000   Jan-20
2020-02-01T05:00:00+0000   Feb-20
2020-01-01T05:00:00+0000   Jan-20
2020-03-01T05:00:00+0000   Mar-20

Note that e.g. -01- refers to January.

Does anyone know how to do this?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Try with this. You only need year and month, so you can use as.Date() and format() to reach what you expect:

#Code
df$date_name <- format(as.Date(df$date),'%b-%Y')

Output:

df
                      date date_name
1 2020-01-01T05:00:00+0000  Jan-2020
2 2020-02-01T05:00:00+0000  Feb-2020
3 2020-01-01T05:00:00+0000  Jan-2020
4 2020-03-01T05:00:00+0000  Mar-2020

Some data used:

#Data
df <- structure(list(date = c("2020-01-01T05:00:00+0000", "2020-02-01T05:00:00+0000", 
"2020-01-01T05:00:00+0000", "2020-03-01T05:00:00+0000")), row.names = c(NA, 
-4L), class = "data.frame")

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...