【问题标题】:Use ddply to find variable values based on a date value使用 ddply 根据日期值查找变量值
【发布时间】:2012-05-15 19:09:54
【问题描述】:

我有一个如下所示的 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")。在不编写讨厌的 for 循环的情况下,我无法将该逻辑合并到 ddply 或以编程方式。不要求算法帮助或有人为我解决它,但希望看到一个使用与此类似的自定义日期逻辑的 ddply 示例。

提前致谢。

【问题讨论】:

  • 找到了一些解决方法。 df$last.date
  • 您能否解释一下您要为ID C 提取的内容,因为04/22/2012 之前的第一个月是03/01/2012,而对于ID C Date.A,没有与此匹配的日期.
  • mondate 库可以处理这个问题:library(mondate); mondate("10-31-2012") - 1

标签: r date plyr


【解决方案1】:

这不适用于lubridateplyr,我什至不确定它是否能解决您的问题。我选择使用 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> 

显然,由于我在您的问题中附加的评论中的原因,有几个月的不适用。

【讨论】:

  • 非常感谢,以后肯定会使用mondate。了解其他人如何解决 R 中的问题总是很有帮助的。
  • 顺便说一句,我从不使用日期,所以可能有更好的解决方案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-03
  • 1970-01-01
相关资源
最近更新 更多