我知道这个问题已经问过好几次了,我看了问题并遵循了建议。然而,我无法解决这个问题。
datetime.csv可以在https://www.dropbox.com/s/6bvhk4kei4pg8zq/datetime.csv上找到
我的代码如下:
jd1 <- read.csv("datetime.csv")
head(jd1)
Date Time
1 20100101 0:00
2 20100101 1:00
3 20100101 2:00
4 20100101 3:00
5 20100101 4:00
6 20100101 5:00
sapply(jd1,class)
> sapply(jd1,class)
Date Time
"integer" "factor"
jd1 <- transform(jd1, timestamp=format(as.POSIXct(paste(Date, Time)), "%Y%m%d %H:%M:%S"))
Error in as.POSIXlt.character(x, tz, ...) :
character string is not in a standard unambiguous format
我尝试了rcs建议的将两列日期和时间数据转换为一列的解决方案,但这似乎给出了一个错误。
非常感谢任何帮助。
谢谢。
您传递给format的格式字符串包括您没有的%S
。但这不会修复错误,因为它来自as.POSIXct
。您需要在那里传递格式字符串,而不是删除对format
函数的调用。
foo <- transform(jd1, timestamp=as.POSIXct(paste(Date, Time), format="%Y%m%d %H:%M"))
str(foo)
与
比较bar <- transform(jd1, timestamp=as.POSIXct(paste(Date, Time), format="%Y%m%d %H:%M:%S"))
str(bar)
和调用format
的结果:
baz <- transform(jd1, timestamp=format(as.POSIXct(paste(Date, Time), format="%Y%m%d %H:%M"), format='%Y%m%d %H:%M:%S'))
str(baz)
如果只是这个文件,您甚至不需要将其读取为csv。下面将执行
# if you are reading just timestamps, you may want to read it as just one column
jd1 <- read.table("datetime.csv", header = TRUE, colClasses = c("character"))
jd1$timestamp <- as.POSIXct(jd1$Date.Time, format = "%Y%m%d,%H:%M")
head(jd1)
## Date.Time timestamp
## 1 20100101,0:00 2010-01-01 00:00:00
## 2 20100101,1:00 2010-01-01 01:00:00
## 3 20100101,2:00 2010-01-01 02:00:00
## 4 20100101,3:00 2010-01-01 03:00:00
## 5 20100101,4:00 2010-01-01 04:00:00
## 6 20100101,5:00 2010-01-01 05:00:00
# if you must read it as seperate columns as you may have other columns in your file
jd2 <- read.csv("datetime.csv", header = TRUE, colClasses = c("character", "character"))
jd2$timestamp <- as.POSIXct(paste(jd2$Date, jd2$Time, sep = " "), format = "%Y%m%d %H:%M")
head(jd2)
## Date Time timestamp
## 1 20100101 0:00 2010-01-01 00:00:00
## 2 20100101 1:00 2010-01-01 01:00:00
## 3 20100101 2:00 2010-01-01 02:00:00
## 4 20100101 3:00 2010-01-01 03:00:00
## 5 20100101 4:00 2010-01-01 04:00:00
## 6 20100101 5:00 2010-01-01 05:00:00
Arun的评论促使我做了一些基准测试…
jd2 <- read.csv("datetime.csv", header = TRUE, colClasses = c("character", "character"))
library(microbenchmark)
microbenchmark(as.POSIXct(paste(jd2$Date, jd2$Time, sep = " "), format = "%Y%m%d %H:%M"), as.POSIXct(do.call(paste, c(jd2[c("Date", "Time")])), format = "%Y%m%d %H:%M"),
transform(jd2, timestamp = as.POSIXct(paste(Date, Time), format = "%Y%m%d %H:%M")), times = 100)
## Unit: milliseconds
## expr min lq median uq max neval
## as.POSIXct(paste(jd2$Date, jd2$Time, sep = " "), format = "%Y%m%d %H:%M") 18.84720 18.87736 18.89542 18.93307 20.99021 100
## as.POSIXct(do.call(paste, c(jd2[c("Date", "Time")])), format = "%Y%m%d %H:%M") 18.94440 18.97917 18.99492 19.02220 21.07320 100
## transform(jd2, timestamp = as.POSIXct(paste(Date, Time), format = "%Y%m%d %H:%M")) 19.05581 19.10230 19.12612 19.16877 21.27490 100