更改日期格式时如何保留Date类?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:
- First, correctly convert your date column to
Datetype (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
- Aggregate your data as before:
agg_df <- aggregate(num~date, data=df, sum)
- 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
Dateclass for all data operations/plotting (so your team’s code works) - Control how dates are displayed in plots or data frame views using
format()oraxis.Date()
内容的提问来源于stack exchange,提问作者Qiyuan

