猿问

在read.table / read.csv中为colClasses参数指定自定义日期格式

在read.table / read.csv中为colClasses参数指定自定义日期格式

题:

有没有办法在read.table / read.csv中使用colClasses参数时指定Date格式?


(我意识到我可以在导入后进行转换,但是有很多这样的日期列,在导入步骤中更容易实现)


例:

我有一个.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


梦里花落0921
浏览 1692回答 3
3回答

杨__羊羊

如果您只想更改1种日期格式,则可以使用该Defaults软件包更改其中的默认格式as.Date.characterlibrary(Defaults)setDefaults('as.Date.character', format = '%d/%M/%Y')dataImport <- read.csv("data.csv", colClasses = c("factor","factor","Date"))str(dataImport)## 'data.frame':&nbsp; &nbsp; 10 obs. of&nbsp; 3 variables:##&nbsp; $ func_loc&nbsp; &nbsp; &nbsp;: Factor w/ 5 levels "3076WAG0003",..: 1 2 3 3 3 3 3 4 4 5##&nbsp; $ order_type&nbsp; &nbsp;: Factor w/ 3 levels "PM01","PM02",..: 3 3 1 1 1 1 2 2 3 1##&nbsp; $ actual_finish: Date, format: "2008-10-15" "2009-10-19" NA "2008-10-11" ...我认为@Greg Snow的答案要好得多,因为它不会改变常用函数的默认行为。
随时随地看视频慕课网APP
我要回答