我有一个如下所示的 data.frame:
ID Date.A Date.B Variable
A 01/01/2012 03/24/2012 Apples
A 02/01/2012 03/24/2012 Oranges
B 01/01/2012 02/04/2012 Bananas
C 01/01/2012 04/22/2012 Apples
A 03/01/2012 03/24/2012 Grapes
B 02/01/2012 02/04/2012 Oranges
D 01/01/2012 03/15/2012 Apples
对于每个 ID,我需要找到与 Date.B 前一个月的第一天相对应的变量。因此,对于 ID A,我需要提取“Oranges”,因为 03/24/2012 - 1 个月 = 02/24/2012,而该月的第一天是 02/01/2012。
使用 lubridate 进行日期计算没有问题:format.Date(df$Date.B - Months(1), format="%Y-%m-01")。我无法将该逻辑合并到 ddply 中或以编程方式合并,而无需编写令人讨厌的 for 循环。不是寻求算法帮助或有人为我解决它,而是希望看到使用与此类似的自定义日期逻辑的 ddply 示例。
提前致谢。
最佳答案
这不适用于 lubridate
或 plyr
,我什至不确定它是否可以解决您的问题。我选择使用 mondate
包的原因是 tcash21 指出的:
10/31/2012 - months(1)
而且我不再使用 plyr 了,所以我对 plyr 的思考也没有那么多。如果您的数据称为 dat:
#Read your data in
dat <- read.table(text="ID Date.A Date.B Variable
A 01/01/2012 03/24/2012 Apples
A 02/01/2012 03/24/2012 Oranges
B 01/01/2012 02/04/2012 Bananas
C 01/01/2012 04/22/2012 Apples
A 03/01/2012 03/24/2012 Grapes
B 02/01/2012 02/04/2012 Oranges
D 01/01/2012 03/15/2012 Apples", header=TRUE)
#This may be unnecessary but when I read your data in the dates were characters
lapply(2:3, function(i) {dat[, i] <<- as.Date(dat[, i], "%m/%d/%Y")})
library(mondate)
prevmon <- as.character(mondate(dat$Date.B) - 1) #get minus 1 month
z <- strsplit(prevmon, "-") #make it that first of that month
dat$Date.C <- as.Date(sapply(z, function(x) paste(x[1], x[2], "01", sep="-")))
key <- split(dat, dat$ID) #make list of data frames by ID
#fruit finding function
fruiter <- function(x) x[match(x[, "Date.C"][1], x[, "Date.A"]), "Variable"]
sapply(key, fruiter)
其产量:
A B C D
Oranges Bananas <NA> <NA>
显然,由于我附加到您的问题的评论中的原因,几个月来一直不适用。
关于r - 使用 ddply 根据日期值查找变量值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10607260/