如何在R中的Date中转换仅数字的年份? [英] how to convert numeric only year in Date in R?

查看:83
本文介绍了如何在R中的Date中转换仅数字的年份?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有年份数字列的数据框,但是我想将它转换为年份日期.

I have a data-frame with column year numeric, but i would like to convert it in year date.

我的数据框

library(tidyverse)
    
date2<-c('01/01/2000','08/08/2000','16/03/2001')
name<-c('A','B','C')
    
df<-data.frame(date2,name)

但是当我执行命令 mutate :

df2<-df%>%
  mutate(date2=dmy(date2))%>%
  mutate(Year2=year(date2))

str(df2)

'data.frame':   3 obs. of  3 variables:
 $ date2: Date, format: "2000-01-01" "2000-08-08" "2001-03-16"
 $ name : chr  "A" "B" "C"
 $ Year2: num  2000 2000 2001

但是我希望Year2是Date而不是数字.

but I would like Year2 to be Date and not numeric.

如何解决这个问题?

推荐答案

我验证了 round_date()带来了问题,因为它的租借日期为2000年到2001年,这可能是一个问题.统计信息.

I verified that round_date() brings problems because it leases dates from the year 2000 to 2001, this can be a problem in the statistics.

根据另一篇文章,我发现 floor_date()可以在同一年取整.

Based on another post I found the floor_date() that rounds up for the same year.

date2<-c('01/01/2000','08/08/2000','16/03/2001')
name<-c('A','B','C')

df<-data.frame(date2,name)

df2 <- df %>%
  mutate(date2 = dmy(date2)) %>%
  mutate(year_date = floor_date(date2,'year'))

df2

看到200-08-08现在四舍五入到2000年

see that 200-08-08 is now rounded up to the year 2000

date2<date> name<chr> year_date<date>
2000-01-01  A   2000-01-01      
2000-08-08  B   2000-01-01      
2001-03-16  C   2001-01-01  

这篇关于如何在R中的Date中转换仅数字的年份?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆