为什么readr将日期对象存储为整数值?

时间:2015-08-20 19:14:07

标签: r dplyr readr

使用readr包读取csv文件时,对象存储为整数值。当我说存储为整数时,我不是指日期列的类,我的意思是基础日期值R存储。如果将一个数据框的日期存储为数值而其他数据为整数,则会阻止使用dplyr连接函数的能力。我在下面列出了一个可重现的例子。我能做些什么来阻止这种行为吗?

library(readr)

df1 <- data.frame(Date = as.Date(c("2012-11-02", "2012-11-04", "2012-11-07", "2012-11-09", "2012-11-11")), Text = c("Why", "Does", "This", "Happen", "?"), stringsAsFactors = F)
class(df1$Date)
# [1] "Date"
dput(df1$Date[1])
# structure(15646, class = "Date")

# Write to dummy csv
write.csv(df1, file = "dummy_csv.csv", row.names = F)

# Read back in data using both read.csv and read_csv
df2 <- read.csv("dummy_csv.csv", as.is = T, colClasses = c("Date", "character"))
df3 <- read_csv("dummy_csv.csv")

# Examine structure of date values
class(df2$Date)
# [1] "Date"
class(df3$Date)
# [1] "Date"

dput(df2$Date[1])
# structure(15646, class = "Date")
dput(df3$Date[1])
# structure(15646L, class = "Date")

# Try to join using dplyr joins
both <- full_join(df2, df3, by = c("Date"))
Error: cannot join on columns 'Date' x 'Date': Cant join on 'Date' x 'Date' because of incompatible types (Date / Date) 

# Base merge works
both2 <- merge(df2, df3, by = "Date")

# converting a POSIXlt object to Date is also stored as numeric
temp_date <- as.Date(as.POSIXct("11OCT2012:19:00:00", format = "%d%b%Y:%H:%M:%S"))
dput(temp_date)
# structure(15624, class = "Date")

根据dplyr回复this issue判断,Hadley认为这是一项功能,但是只要您的日期值以不同的方式存储,您就无法合并它们,而且我没有&# 39; t想出了一种将整数日期对象转换为数字对象的方法。反正有没有阻止readr包执行此操作或以任何方式将存储为整数的Date对象转换为数值?

1 个答案:

答案 0 :(得分:4)

根据the big man himself这是dplyr而不是readr的错误。他说在读取文件时存储数值与整数值是可以的,但是dplyr应该能够像merge那样处理差异。