在R中遍历日期列表时输出数字17641的原因咨询
Great question! Let's break down exactly what's happening here.
First, the core concept: in R, Date objects are stored internally as integers. These integers represent the number of days since a specific reference date (called the "origin"). By default, R uses the Unix epoch—1970-01-01—as this origin point.
Why does R do this?
Storing dates as integers makes date calculations (like adding days, finding the difference between two dates, or sorting) extremely efficient. Instead of dealing with complex string parsing for every operation, R can rely on simple arithmetic with the underlying integer values.
When do you see the numeric value instead of a formatted date?
Most of the time, R will display Date objects in a human-readable string format (like 2017-03-08). But you might see the raw numeric value in a few scenarios:
- If you explicitly convert the Date to a numeric type using
as.numeric(). - If there’s an accidental type coercion (e.g., combining Date objects with non-Date objects in a vector, though R usually tries to preserve the Date class when possible).
- If there’s a mistake in your date parsing code—like the typo in your snippet—that leads to unintended date interpretation.
Looking at your code:
test_list <- c(as.Date('2017-03-08','2017-03-08' )) for(el in test_list){ print(el) }
The issue here is that the second argument to as.Date() is supposed to be a format string (like "%Y-%m-%d"), not another date string. When you pass '2017-03-08' as the format, R tries to parse the first string using that literal format, which leads to an unexpected date result. The numeric value 17641 you see corresponds to 2018-05-20—that’s exactly 17641 days after the 1970-01-01 origin.
Corrected code example
To create a vector of the 2017-03-08 date correctly, use:
# Correct way to make a vector of Date objects test_list <- rep(as.Date('2017-03-08'), 2) for(el in test_list){ print(el) }
Running this will print the formatted date 2017-03-08 twice, as expected.
How to verify the numeric ↔ date relationship
You can easily convert between the numeric and date formats to confirm:
# Get numeric value of a specific date as.numeric(as.Date("2018-05-20")) # Returns 17641 # Convert numeric back to a date as.Date(17641, origin = "1970-01-01") # Returns "2018-05-20"
So to wrap up: R uses integers for dates under the hood to keep operations fast and simple. The numeric output you encountered was likely due to a typo in your date parsing code, which caused R to interpret the date incorrectly and show the underlying integer value.
内容的提问来源于stack exchange,提问作者user1700890

