我是R的新手,并且一直在努力解决这个问题。试图找到跨地方的解决方案,但不能 我有一个包含多个csv文件的文件夹(大约158个)。每个csv都有一个包含日期和时间的列。我发现日期的格式在csv文件中不是标准的,这会影响我的分析。示例:
>head(file1) # date format is in MONTH/day/year
DateTime Value
6/2/14 11:00:01 PM 24.111
6/3/14 1:30:01 AM 21.61
6/3/14 4:00:01 AM 20.609
>head(file2) # date format is in day/MONTH/year
DateTime Value
03/06/14 1:30:01 AM 21.588
03/06/14 4:00:01 AM 20.086
03/06/14 6:30:01 AM 18.584
我做了以下循环来绑定文件。
>files.names<-list.files(getwd(),pattern="*.csv")
>theList <- lapply(files.names,function(x){
> theData <- read.csv(x,skip=18) })
>theResult <- do.call(rbind,theList)
>head(theResult)
Date.Time Value
1 6/2/14 11:00:01 PM 24.111
2 6/3/14 1:30:01 AM 21.610
3 6/3/14 4:00:01 AM 20.609
4 6/3/14 6:30:01 AM 19.107
5 6/3/14 9:00:01 AM 19.608
6 6/3/14 11:30:01 AM 20.609
我的想法:我猜测必须有一种方法可以在绑定它们之前在每个csv的循环中标准化Date.Time
列的格式。也就是说,我认为我必须在do.call(rbind,theList)
之前做到这一点,但不确定如何(或者是否可能)。
在Excel中格式化每个csv文件将是一个痛苦的屁股,所以我将感谢一些帮助:P。
答案 0 :(得分:2)
根据建议,使用read.csv
包中的parse_date_time
函数,在lubridate
之后添加一行额外的代码,可以做到正确。
>files.names<-list.files(getwd(),pattern="*.csv")
>theList <- lapply(files.names,function(x){
>theData <- read.csv(x,skip=18)
>theData$Date.Time<-parse_date_time(x = theData$Date.Time,
orders = c("mdy HMS %p", "dmy HMS %p"), local = eng") }) ###extra line
>theResult <- do.call(rbind,theList)
我的猜测是,根据mdy
中的dmy
参数,R可以确定何时应该是orders
或parse_date_time
。
答案 1 :(得分:1)
需要使用?strptime
帮助页面中的正确格式字符串:
file1$DateTime <- as.POSIXct( file1$DateTime , format="%m/%d/%y %I:%M:%S %p")
file2$DateTime <- as.POSIXct( file1$DateTime , format="%d/%m/%y %I:%M:%S %p")
日期时间输入的脱脂格式为24小时时间的YYYY-MM-DD HH:MM:SS。如果您有AM / PM指示器,则需要使用%I 12小时格式规范。
> file1
DateTime Value
1 2014-06-02 23:00:01 24.111
2 2014-06-03 01:30:01 21.610
3 2014-06-03 04:00:01 20.609
> file2
DateTime Value
1 2014-06-02 23:00:01 21.588
2 2014-06-03 01:30:01 20.086
3 2014-06-03 04:00:01 18.584
然后使用do.call(rbind, list(file1,file2))
获取:
DateTime Value
1 2014-06-02 23:00:01 24.111
2 2014-06-03 01:30:01 21.610
3 2014-06-03 04:00:01 20.609
4 2014-06-02 23:00:01 21.588
5 2014-06-03 01:30:01 20.086
6 2014-06-03 04:00:01 18.584