aggregate() 和 ave() 与日期的组合问题

Problem with the combination of aggregate() and ave() with dates

我在同一个函数中将 aggregate()ave() 与日期(格式 2020-03-16)结合使用时遇到一些问题,如果我做:

#Raw nest data
raw.Atta<- read.csv("https://raw.githubusercontent.com/Leprechault/trash/main/cres_ninho_ed.csv", sep=";", h=T)
str(raw.Atta)

## Create the days in each class
Atta.db.1 <- merge(raw.Atta, 
  within(
    aggregate(data ~ ninho + classe, raw.Atta, max),
    step3 <- ave(data, ninho, FUN = function(x) diff(c(0, x)))
  ),
  by = c("ninho", "classe"),
  all = TRUE
)

Error in r[i1] - r[-length(r):-(length(r) - lag + 1L)] :
    non-numeric argument to binary operator error

然后我将日期更改为另一种格式:

raw.Atta <- raw.Atta %>%
  mutate(date = as.POSIXlt(data, format = "%Y-%m-%d")) # convert to datetime object

Error in model.frame.default(formula = data ~ ninho + classe, data = raw.Atta) :

产生新问题!!

有什么想法吗?

提前致谢!

试试这个。这个问题起源于 diff(),因为它需要一个日期变量,而你的是一个字符:

#Raw nest data
raw.Atta<- read.csv("https://raw.githubusercontent.com/Leprechault/trash/main/cres_ninho_ed.csv", sep=";", h=T)
str(raw.Atta)

## Create the days in each class
Atta.db.1 <- merge(raw.Atta, 
                   within(
                     aggregate(data ~ ninho + classe, raw.Atta, max),
                     step3 <- ave(data, ninho, FUN = function(x) diff(c(0, as.Date(x))))
                   ),
                   by = c("ninho", "classe"),
                   all = TRUE
)