| weight | Time | Chick | Diet | |-----------|----------|---------|---------| | 42 | 0 | 1 | 1 | | 51 | 2 | 1 | 1 | | 59 | 4 | 1 | 1 | | 64 | 6 | 1 | 1 | | 76 | 8 | 1 | 1 | | 93 | 10 | 1 | 1 | | 106 | 12 | 1 | 1 | | 125 | 14 | 1 | 1 | | 149 | 16 | 1 | 1 | | 171 | 18 | 1 | 1 | | 199 | 20 | 1 | 1 | | 205 | 21 | 1 | 1 | | 40 | 0 | 2 | 1 | | 49 | 2 | 2 | 1 |
我需要取当前的重量并在时间0减去重量。时间间隔每12行重置一次。将其变为WeightGain列。请帮我在r。
中这样做答案 0 :(得分:-1)
我们根据时间0的出现创建一个分组变量,然后从第一个'权重'中减去'权重'
library(dplyr)
df1 %>%
group_by(grp = cumsum(Time==0)) %>%
mutate(WeightGain = weight - first(weight))
# A tibble: 24 x 6
# Groups: grp [2]
# weight Time Chick Diet grp newweight
# <int> <int> <int> <int> <int> <int>
# 1 42 0 1 1 1 0
# 2 51 2 1 1 1 9
# 3 59 4 1 1 1 17
# 4 64 6 1 1 1 22
# 5 76 8 1 1 1 34
# 6 93 10 1 1 1 51
# 7 106 12 1 1 1 64
# 8 125 14 1 1 1 83
# 9 149 16 1 1 1 107
#10 171 18 1 1 1 129
# ... with 14 more rows