Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.3k 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 Reply

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")

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...