首页 > 解决方案 > aggregate() 和 ave() 与日期组合的问题

问题描述

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) :

产生新问题!!

请一些想法?

提前致谢!

标签: rdplyrdatediff

解决方案


尝试这个。这个问题的根源在于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
)

推荐阅读