简体   繁体   English

从R中的CSV文件读取时间

[英]Reading time from CSV file in R

I want to read a CSV file separated by ";" 我想读取一个以“;”分隔的CSV文件 which contains four columns, such as: 其中包含四列,例如:

16/12/2006;17:24:00;0;1
16/12/2006;17:25:00;2;3
16/12/2006;17:26:00;4;5

but I want a dataframe with 3 columns rather than 4 (that is, merge the date and hour of the two first columns into a single one). 但是我想要一个3列而不是4列的数据框(也就是说,将前两列的日期和小时合并为一个)。

So far, I have come up with this portion of code inspired by Specify custom Date format for colClasses argument in read.table/read.csv to read the data. 到目前为止,我提出了这部分代码,其灵感来自在read.table / read.csv中为colClasses参数指定自定义日期格式来读取数据。 Then, I'd merge the two columns somehow. 然后,我将以某种方式合并两列。

setClass("myDate")
setAs("character","myDate", function(from) as.Date(from, format="%d/%m/%Y") )
setClass("myTime")
setAs("character","myTime", function(from) as.Date(from, format="%H:%M:%S") )

data <- read.table(file = "file.csv", header = FALSE, sep = ";", colClasses =  c("myDate", "myTime", "numeric", "numeric"))

However, the resulting data frame does have a column V2 in which the hour is not properly read. 但是,结果数据帧确实具有第V2列,其中无法正确读取小时。

          V1         V2 V3 V4
1 2006-12-16 2016-03-04  0  1
2 2006-12-16 2016-03-04  2  3
3 2006-12-16 2016-03-04  4  5

Is the myTime class badly defined? myTime类定义不正确吗? If so, how should I change it? 如果是这样,我应该如何更改?

Is there a particular reason why you want to do this during the import, and not after? 您为什么要在导入期间而不是之后执行此特定操作? It seems much easier to import the 4 columns, merge the date and time together using paste , and then use the lubridate package and its dmy_hms function to convert to proper date-time: 导入4列,使用paste合并日期和时间,然后使用lubridate包及其dmy_hms函数将其转换为正确的日期时间似乎要容易得多:

require(lubridate)
data <- read.table(file = "file.csv", header = FALSE, sep = ";")
data$date_time <- paste(data$V1, data$V2)
data$date_time <- dmy_hms(data$date_time)
data[1:2] <- list(NULL)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM