You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

更改日期格式时如何保留Date类?R语言技术求助

How to Keep Date Class and Display in dd-mm-yyyy Format in R

Great question—this is a super common point of confusion with R's Date type, so let's break this down clearly:

First, Understand R's Date Class

R's Date objects don’t actually store a "display format" like dd-mm-yyyy or yyyy-mm-dd. Under the hood, they’re just numeric values representing days since 1970-01-01. The yyyy-mm-dd you see when printing is just R’s default printing behavior, not a property of the date itself.

So when you run df$date <- as.Date(df$date, "%d.%m.%Y"), you’re already doing the right thing: converting your factor dates to proper Date objects that R can correctly sort, plot, and calculate with. The default display format doesn’t affect functionality—it’s just how R shows you the dates.

Solution 1: Keep Date Class, Customize Plot Axes

Your main goal is to have dates display as dd-mm-yyyy in plots (while keeping the Date class so your team’s code works). Here’s how to adjust your plotting code to do that:

  1. First, correctly convert your date column to Date type (this preserves the date’s numerical meaning):
df <- data.frame(date=c("31.08.2011", "31.07.2011", "30.06.2011", "30.06.2011"), num=as.numeric(c("3","6","9", "4")))
df$date <- as.Date(df$date, "%d.%m.%Y") # This gives you proper Date objects
  1. Aggregate your data as before:
agg_df <- aggregate(num~date, data=df, sum)
  1. Plot with a custom x-axis to show dd-mm-yyyy:
# Plot without the default x-axis (xaxt="n")
plot(num ~ date, data = agg_df, type = "b", xaxt = "n")
# Add a custom Date axis with your desired format
axis.Date(side = 1, at = agg_df$date, format = "%d-%m-%Y")

This keeps your date column as Date (so sorting and plotting logic works correctly) while displaying dates in your team’s preferred format on the plot.

Solution 2: Add a Display-Only Column (For Data Frame Viewing)

If you also want to see dd-mm-yyyy when you print the data frame, create a separate character column for display—don’t overwrite the original Date column (that would break plotting/calculations):

df$display_date <- format(df$date, "%d-%m-%Y")

Now df$date stays a Date object for all functional use, and df$display_date shows the format your team prefers when you view the data.

Key Takeaway

You can’t make a Date object store the dd-mm-yyyy format (since it’s a numeric under the hood), but you absolutely can:

  • Keep the Date class for all data operations/plotting (so your team’s code works)
  • Control how dates are displayed in plots or data frame views using format() or axis.Date()

内容的提问来源于stack exchange,提问作者Qiyuan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 08:34:56