我有一个仪器,可以将数据导出为混乱的时间格式。我需要将
date
和time
向量合并成一个新的datetime
向量,并使用以下POSIXct
格式:%Y-%m-%d %H:%M:%S
。出于好奇心,我尝试了三种不同的方法来实现这一点,分别使用as.POSIXct()
、strftime()
和strptime()
函数。当使用下面的示例数据时,只有as.POSIXct()
和strftime()
函数能够正常工作,但我很想知道为什么strptime()
会产生NAs
?此外,我无法使用as.POSIXct()
将strftime()
输出转换为POSIXct
对象...
当在我的真实数据上尝试这些相同的函数(我只提供了前四行)时,我遇到了完全不同的问题。只有strftime()
函数有效。由于某种原因,as.POSIXct()
函数也会产生NAs
,这是我实际需要用于将我的datetime
转换为POSIXct
对象的唯一命令...
似乎这些函数之间存在微妙的差别,我想知道如何更有效地使用它们。谢谢!
可重现示例:
## Creating dataframe:
date <- c("2017-04-14", "2017-04-14","2017-04-14","2017-04-14")
time <- c("14:24:24.992000","14:24:25.491000","14:24:26.005000","14:24:26.511000")
value <- c("4.106e-06","4.106e-06","4.106e-06","4.106e-06")
data <- data.frame(date, time)
data <- data.frame(data, value) ## I'm sure there is a better way to combine three vectors...
head(data)
## Creating 3 different datetime vectors:
## This works in my example code, but not with my real data...
data$datetime1 <- as.POSIXct(paste(data$date, data$time), format = "%Y-%m-%d %H:%M:%S",tz="UTC")
class(data$datetime1)
## This is producing NAs, and I'm not sure why:
data$datetime2 <- strptime(paste(data$date, data$time), format = "%Y-%m-%d %H:%M%:%S", tz = "UTC")
class(data$datetime2)
## This is working just fine
data$datetime3 <- strftime(paste(data$date, data$time), format = "%Y-%m-%d %H:%M%:%S", tz = "UTC")
class(data$datetime3)
head(data)
## Since I cannot get the as.POSIXct() function to work with my real data, I tried this workaround. Unfortunately I am running into trouble...
data$datetime4 <- as.POSIXct(x$datetime3, format = "%Y-%m-%d %H:%M%:%S", tz = "UTC")
真实数据链接: 这里
使用real_data.txt的示例:
## Reading in the file:
fpath <- "~/real_data.txt"
x <- read.csv(fpath, skip = 1, header = FALSE, sep = "", stringsAsFactors = FALSE)
names(x) <- c("date","time","bscat","scat_coef","pressure_mbar","temp_K","CH1","CH2") ## This is data from a Radiance Research Integrating Nephelometer Model M903 for anyone who is interested!
## If anyone could get this to work that would be awesome!
x$datetime1 <- as.POSIXct(paste(x$date, x$time), format = "%Y-%m-%d %H:%M%:%S", tz = "UTC")
## This still doesn't work...
x$datetime2 <- strptime(paste(x$date, x$time), format = "%Y-%m-%d %H:%M%:%S", tz = "UTC")
## This works:
x$datetime3 <- strftime(paste(x$date, x$time), format = "%Y-%m-%d %H:%M%:%S", tz = "UTC")
## But I cannot convert from strftime character to POSIXct object, so it doesn't help me at all...
x$datetime4 <- as.POSIXct(x$datetime3, format = "%Y-%m-%d %H:%M%:%S", tz = "UTC")
head(x)
解决方案:
我没有为as.POSIXct()
函数提供正确的格式字符串。一旦我将%Y-%m-%d %H:%M%:%S
更改为%Y-%m-%d %H:%M:%S
,data$datetime2
、data$datetime4
、x$datetime1
和x$datetime2
就正常工作了!非常感谢PhilC
进行调试!