对于每只鸟,我想计算不同日期(Tb_Periods)的平均每小时体温(Tb)测量值之间的差异。我的目标是能够比较BirdX的Tb从0900 PreI到09:00 DayI,10:00 PreI到10:00 PostI等的变化.Tb_Period表示操作前的时间(PreI),操作日(DayI)和后期操作(PostI)。我最初的df:
Date_Time Bird_ID Tb Hour Treatment Tb_Period
2018-04-04 11:01:39 3282 42.2 11 Control PreI
2018-04-04 12:31:51 3282 41.2 12 Control PreI
....
2018-04-05 09:16:54 3282 41.9 9 Control DayI
....
2018-04-06 08:09:57 3282 41.4 8 Control PostI
到目前为止我做了什么:每只小鸟在48小时的时间内每10分钟测量一次体温,所以我首先使用dplyr计算每只小鸡每小时的平均Tb:
Tb_Averages <- TbData %>% group_by(Tb_Period, Hour, Bird_ID, Treatment)%>%
summarize(meanHourTb = mean(Tb))
结果df:
Tb_Period Hour Bird_ID Treatment meanHourTb
PreI 9 3500 LPS 41.55000
PreI 10 3500 LPS 41.75000
...
DayI 9 3500 LPS 40.88182
DayI 10 3500 LPS 41.24000
现在我想要的是一个看起来像这样的df:
Bird_ID Hour Treatment Tb_Diff
3500 9 LPS -.67 (40.88-41.55)
3282 9 LPS .5 (e.g.)
根据Calculate difference between values in consecutive rows by group的回答,我尝试了以下各种变体(使用dplyrs排列函数):
Tb_Averages <- Tb_Averages %>%
group_by(Tb_Period, Bird_ID, Hour) %>%
mutate(Tb_Diff = c(NA, diff(meanHourTb))))
但要继续为Tb_Diff列获取NAs。解决此问题的最佳方法是什么(理想情况下使用dplyr)?
答案 0 :(得分:2)
你快到了!关键是将Tb_Period转换为有序因子,这样PreI
被视为&#34;小于&#34; DayI
,反过来小于PostI
。一旦建立,我们可以按每个鸟和小时分组,并按Tb_Period排序,以确保以正确的顺序计算差异:
df <- read.table(text = 'Tb_Period Hour Bird_ID Treatment meanHourTb
PreI 9 3500 LPS 41.55000
PreI 10 3500 LPS 41.75000
DayI 9 3500 LPS 40.88182
DayI 10 3500 LPS 41.24000', header = T, stringsAsFactors = F)
df <- df %>%
mutate(Tb_Period = factor(Tb_Period, c('PreI', 'DayI', 'PostI'), ordered = T)) %>%
group_by(Bird_ID, Hour) %>%
mutate(diff = meanHourTb - lag(meanHourTb, 1))
# A tibble: 4 x 6
# Groups: Bird_ID, Hour [2]
Tb_Period Hour Bird_ID Treatment meanHourTb diff
<ord> <int> <int> <chr> <dbl> <dbl>
1 PreI 9 3500 LPS 41.55000 NA
2 PreI 10 3500 LPS 41.75000 NA
3 DayI 9 3500 LPS 40.88182 -0.66818
4 DayI 10 3500 LPS 41.24000 -0.51000