我有一个csv文件,内容如下:
VA1,VA2,2014-05-24,,2014-05-22 15:50:16
VA2,VA1,2014-05-24,2014-05-26,2014-05-22 15:50:16
我怎么读?
标准read.csv
无法识别日期YYYY-MM-DD。我曾尝试使用read.zoo
,但我不确定如何:
这是我尝试过的:
library(zoo)
colClasses <- c("factor", "factor", "Date", "Date", "Date")
fmt <- "%Y-%m-%d"
z <- read.zoo("file.csv", header = FALSE, sep = ",", quote = "", format = fmt, tz = "", colClasses = colClasses)
答案 0 :(得分:1)
您无法使用read.zoo
来阅读该类数据。它意味着时间序列。请尝试以下方法。不需要包裹。下面的代码编写为自包含,但text = Lines
部分可以用文件名替换,例如read.table("myfile.dat", ...whatever...)
:
Lines <- "VA1,VA2,2014-05-24,,2014-05-22 15:50:16
VA2,VA1,2014-05-24,2014-05-26,2014-05-22 15:50:16"
DF <- read.table(text = Lines, sep = ",", as.is = TRUE, na.strings = "")
transform(DF, V3 = as.Date(V3), V4 = as.Date(V4), V5 = as.POSIXct(V5))
,并提供:
V1 V2 V3 V4 V5
1 VA1 VA2 2014-05-24 <NA> 2014-05-22 15:50:16
2 VA2 VA1 2014-05-24 2014-05-26 2014-05-22 15:50:16
答案 1 :(得分:0)
您应该能够使用read.csv
阅读该表格,然后将第3列和第4列设置为strptime
的日期和日期时间对象:
第3栏:
data[,3] = as.POSIXct(as.character(data[,3]))
第4栏:
data[,4] = as.POSIXct(as.character(data[,4]))