我有一种仪器,以不规则的时间格式导出数据。我需要将date
和time
载体组合成以下POSIXct
格式的新的datetime
载体:%Y-%m-%d %H:%M:%S
。出于好奇,我试图用三种不同的方式做到这一点,使用as.POSIXct()
,strftime()
和strptime()
。当使用我的示例数据下面,只有as.POSIXct()
和strftime()
功能工作,但我很好奇为什么strptime()
生产NAs
?此外,我不能strftime()
输出转换成使用as.POSIXct()
一个POSIXct
对象...将日期时间从字符转换为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")
链接到真实数据: here
实施例使用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
的调试!
**谢谢!**我的大脑在对我玩技巧!出于某种原因,我只是无法看到它,但现在你已经指出了这一点,它非常明显!哈哈我想我现在要休息一下...... – spacedSparking