根据日期从R中的date.frame中提取记录

时间:2012-01-19 09:45:54

标签: r date

我有data.frame如下:

dat <- structure(list(id = 1:4, date = structure(list(sec = c(0, 0, 
0, 0), min = c(0L, 0L, 0L, 0L), hour = c(0L, 0L, 0L, 0L), mday = 1:4, 
    mon = c(0L, 0L, 0L, 0L), year = c(110L, 110L, 110L, 110L), 
    wday = c(5L, 6L, 0L, 1L), yday = 0:3, isdst = c(0L, 0L, 0L, 
    0L)), .Names = c("sec", "min", "hour", "mday", "mon", "year", 
"wday", "yday", "isdst"), class = c("POSIXlt", "POSIXt")), name = c("george", 
"paul", "john", "ringo")), .Names = c("id", "date", "name"), row.names = c(NA, 
-4L), class = "data.frame")

要选择我可以使用的最早或最近日期的行:

分别为

dat[(dat$date ==min(dat$date)),]dat[(dat$date ==max(dat$date)),]

是否有办法获取其他日期的记录,例如第二个最旧的或最近的第二个。

感谢。

1 个答案:

答案 0 :(得分:4)

您可以对data.frame进行排序并获取第一行或最后一行。

dat <- dat[ order(dat$date), ]
dat[1,]  # Oldest
dat[2,]  # Second oldest
n <- dim(dat)[1]
dat[n,]  # Latest
dat[n-1,] # Second most recent