2017-06-15 81 views
2

我有每天育种配对egg_number的数据(Parents)。我试图根据下面的数据“egg_output1”确定从父母分组出来的蛋之间的平均时间(以天为单位)。如何获得分组事件频率?

因此,基本上,按照时间顺序排列数据后,按父母分组的行日期之间的平均差异。这可能吗??

Tank  Parents       date   egg_number 
1: P3-T25 DON_AGEM_031FXDON_AGEM_036M  2017-06-03  2 
2: P3-T25 DON_AGEM_031FXDON_AGEM_036M  2017-06-03  1 
3: P3-T25 DON_AGEM_031FXDON_AGEM_036M  2017-05-23  1 

我曾尝试使用下面的代码尝试:

as.Date(egg_output1$date) 
egg <- egg_output1[order(egg_output1$date),] 
ddply(
    egg, 
    c("Parents"), 
    summarize, 
    average = mean(diff(date)) 
) 

但这返回NA与以下警告:

Warning messages: 
1: In mean.default(diff(date)) : argument is not numeric or logical: returning NA 
2: In mean.default(diff(date)) : argument is not numeric or logical: returning NA 
3: In mean.default(diff(date)) : argument is not numeric or logical: returning NA 

样本数据:

eggs <- data.frame(
    parents = sample(c("005Fx001M", "008Fx006M","028Fx026M"), 10, replace = TRUE), 
    date = sample(seq(as.Date('2016/01/01'), as.Date('2017/01/01'), by="day"), 10), 
    egg_number = sample(c("1", "2"), 10, replace = TRUE)) 
+1

您能否包含一小部分数据样本? – RobertMc

+0

请阅读[如何在R中创建一个很好的重现示例](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) – Masoud

+1

尝试'。(父母),而不是'c(“父母”)'。这对我的样本数据很有帮助,尽管它会成为你的第一个例子的“。(Parents)”。 –

回答

0

Calculating difference row values by group in R

> dt=NULL 
> dt$Tank=rep("P3-T25",3) 
> dt$Parents=rep("DON_AGEM_031FXDON_AGEM_036M",3) 
> dt$Date=c("2017-06-3","2017-06-3","2017-05-3") 
> dt$egg_number=c(2,1,1) 
> dt=as.data.frame(dt) 
> dt 
    Tank      Parents  Date egg_number 
1 P3-T25 DON_AGEM_031FXDON_AGEM_036M 2017-06-3   2 
2 P3-T25 DON_AGEM_031FXDON_AGEM_036M 2017-06-3   1 
3 P3-T25 DON_AGEM_031FXDON_AGEM_036M 2017-05-3   1 


library(data.table) 

dt=data.table(dt) 
setkey(dt,Parents) 
library(lubridate) 
    > dt$Date=ymd(dt$Date) 
> dt[,diff:=c(NA,diff(Date)),by=Parents] 
> dt 
    Tank      Parents  Date egg_number diff 
1: P3-T25 DON_AGEM_031FXDON_AGEM_036M 2017-06-03   2 NA 
2: P3-T25 DON_AGEM_031FXDON_AGEM_036M 2017-06-03   1 0 
3: P3-T25 DON_AGEM_031FXDON_AGEM_036M 2017-05-03   1 -31