【发布时间】:2014-12-04 01:37:09
【问题描述】:
问题:
在 read.table/read.csv 中使用 colClasses 参数时,有没有办法指定日期格式?
(我意识到我可以在导入后进行转换,但是有很多这样的日期列,在导入步骤中会更容易)
示例:
我有一个带有日期列的 .csv,格式为 %d/%m/%Y。
dataImport <- read.csv("data.csv", colClasses = c("factor","factor","Date"))
这会导致转换错误。例如,15/07/2008 变为 0015-07-20。
可重现的代码:
data <-
structure(list(func_loc = structure(c(1L, 2L, 3L, 3L, 3L, 3L,
3L, 4L, 4L, 5L), .Label = c("3076WAG0003", "3076WAG0004", "3076WAG0007",
"3076WAG0009", "3076WAG0010"), class = "factor"), order_type = structure(c(3L,
3L, 1L, 1L, 1L, 1L, 2L, 2L, 3L, 1L), .Label = c("PM01", "PM02",
"PM03"), class = "factor"), actual_finish = structure(c(4L, 6L,
1L, 2L, 3L, 7L, 1L, 8L, 1L, 5L), .Label = c("", "11/03/2008",
"14/08/2008", "15/07/2008", "17/03/2008", "19/01/2009", "22/09/2008",
"6/09/2007"), class = "factor")), .Names = c("func_loc", "order_type",
"actual_finish"), row.names = c(NA, 10L), class = "data.frame")
write.csv(data,"data.csv", row.names = F)
dataImport <- read.csv("data.csv")
str(dataImport)
dataImport
dataImport <- read.csv("data.csv", colClasses = c("factor","factor","Date"))
str(dataImport)
dataImport
这是输出的样子:
【问题讨论】:
-
一种骇人听闻的方法是创建您自己的
read.table版本并添加一个format参数,该参数传递给as.Date。不过,如果有我没有想到的更好的方法,我不会感到惊讶。
标签: r date read.table read.csv