我有日志数据文件,它们只存储一天中的时间以及连续几天的一些数据。
V1 V2
1 11:40:34 1
2 11:52:28 2
3 23:37:19 37
4 23:57:27 38
5 00:17:35 39
6 00:37:43 40
7 00:57:52 41
8 01:18:00 42
9 04:17:03 52
10 17:47:29 18
11 21:29:00 29
12 23:49:58 36
13 00:10:06 37
14 00:30:14 38
15 11:14:39 70
16 18:20:09 1
17 23:28:15 17
18 23:48:24 18
19 00:08:32 19
20 00:28:40 20
21 02:49:38 27
22 08:11:51 43
23 15:14:45 64
24 17:15:34 70
我知道文件创建时的“开始日期”,需要为每一行分配正确的日期。我想出了一种使用循环的方法:
data <- structure(list(V1 = structure(
c(13L, 14L, 21L, 24L, 3L, 6L, 7L,
8L, 10L, 17L, 19L, 23L, 2L, 5L,
12L, 18L, 20L, 22L, 1L, 4L, 9L,
11L, 15L, 16L), .Label =
c("00:08:32", "00:10:06", "00:17:35",
"00:28:40", "00:30:14", "00:37:43", "00:57:52", "01:18:00", "02:49:38",
"04:17:03", "08:11:51", "11:14:39", "11:40:34", "11:52:28", "15:14:45",
"17:15:34", "17:47:29", "18:20:09", "21:29:00", "23:28:15", "23:37:19",
"23:48:24", "23:49:58", "23:57:27"), class = "factor"),
V2 = c(1L, 2L, 37L, 38L, 39L, 40L, 41L, 42L, 52L, 18L, 29L, 36L, 37L, 38L,
70L, 1L, 17L, 18L, 19L, 20L, 27L, 43L, 64L, 70L)), .Names =
c("V1", "V2"), class = "data.frame", row.names = c(NA, -24L))
startdate <- as.Date("2010-10-14")
data$day <- startdate
k <- 0
for (i in 1:length(data$V1)-1){
if (as.POSIXlt(paste(startdate,data$V1[i],sep=" ")) >
as.POSIXlt(paste(startdate,data$V1[i+1],sep=" ")))
k <- k+1
data$day[i+1] <- startdate + k
}
这给出了所需的结果,然后我可以使用它来创建正确的 POSIXlt 日期列(包括日期和时间)。
V1 V2 day
1 11:40:34 1 2010-10-14
2 11:52:28 2 2010-10-14
3 23:37:19 37 2010-10-14
4 23:57:27 38 2010-10-14
5 00:17:35 39 2010-10-15
6 00:37:43 40 2010-10-15
7 00:57:52 41 2010-10-15
8 01:18:00 42 2010-10-15
9 04:17:03 52 2010-10-15
10 17:47:29 18 2010-10-15
11 21:29:00 29 2010-10-15
12 23:49:58 36 2010-10-15
13 00:10:06 37 2010-10-16
14 00:30:14 38 2010-10-16
15 11:14:39 70 2010-10-16
16 18:20:09 1 2010-10-16
17 23:28:15 17 2010-10-16
18 23:48:24 18 2010-10-16
19 00:08:32 19 2010-10-17
20 00:28:40 20 2010-10-17
21 02:49:38 27 2010-10-17
22 08:11:51 43 2010-10-17
23 15:14:45 64 2010-10-17
24 17:15:34 70 2010-10-17
不过,我想摆脱循环,并感谢任何关于如何做到这一点的“R 风格”的想法。