计算数据长格式时的费率

时间:2018-04-20 16:53:14

标签: r if-statement dplyr grouping

我的数据样本可用here

我正在尝试计算每个wt的增长率(重量变化(squirrel))。

当我以宽幅格式获取数据时:

squirrel    fieldBirthDate  date1       date2       date3   date4   date5   date6   age1    age2    age3    age4    age5    age6    wt1     wt2     wt3 wt4 wt5 wt6 litterid
22922         2017-05-13    2017-05-14  2017-06-07  NA      NA      NA      NA      1       25      NA      NA      NA      NA      12      52.9    NA  NA  NA  NA  7684
22976         2017-05-13    2017-05-16  2017-06-07  NA      NA      NA      NA      3       25      NA      NA      NA      NA      15.5    50.9    NA  NA  NA  NA  7692
22926         2017-05-13    2017-05-16  2017-06-07  NA      NA      NA      NA      0       25      NA      NA      NA      NA      10.1    48      NA  NA  NA  NA  7719

我可以使用以下代码计算增长率:

library(dplyr)

#growth rate between weight 1 and weight 3, divided by age when weight 3 is recorded
growth <- growth %>%
    mutate (g.rate=((wt3-wt1)/age3))

#growth rate between weight 1 and weight 2, divided by age when weight 2 is recorded
merge.growth <- merge.growth %>%
    mutate (g.rate=((wt2-wt1)/age2))

但是,当数据为长格式时(我之后运行的分析所需的格式):

squirrel    litterid    date    age wt
22922       7684    2017-05-13  0   NA
22922       7684    2017-05-14  1   12
22922       7684    2017-06-07  25  52.9
22976       7692    2017-05-13  1   NA
22976       7692    2017-05-16  3   15.5
22976       7692    2017-06-07  25  50.9
22926       7719    2017-05-14  0   10.1
22926       7719    2017-06-08  25  48

我无法使用上面使用的mutate函数。我希望创建一个包含增长率的新列,如下所示:

squirrel    litterid    date    age wt      g.rate
22922       7684    2017-05-13  0   NA      NA
22922       7684    2017-05-14  1   12      NA
22922       7684    2017-06-07  25  52.9    1.704
22976       7692    2017-05-13  1   NA      NA
22976       7692    2017-05-16  3   15.5    NA
22976       7692    2017-06-07  25  50.9    1.609
22926       7719    2017-05-14  0   10.1    NA
22926       7719    2017-06-08  25  48      1.516
22758       7736    2017-05-03  0   8.8     NA  
22758       7736    2017-05-28  25  43      1.368
22758       7736    2017-07-05  63  126     1.860
22758       7736    2017-07-23  81  161     1.879
22758       7736    2017-07-26  84  171     1.930

我一直在计算excel中的增长率(每个wt和第一次称重之间的增长),但是我想在R中进行计算,因为我有大量的松鼠到与...合作。我怀疑if else loops可能是去这里的方式,但我并不精通这种编码。欢迎任何建议或想法!

2 个答案:

答案 0 :(得分:4)

您可以使用group_by为每只松鼠计算:

group_by(df, squirrel) %>% 
    mutate(g.rate = (wt - nth(wt, which.min(is.na(wt)))) / 
                    (age - nth(age, which.min(is.na(wt)))))

NaN项为age项为零,但如果您需要NA,则可以将其更改为df$g.rate[is.nan(df$g.rate)] <- NA

答案 1 :(得分:1)

替代使用data.table及其功能“shift”,它采用前一行

library(data.table)
df= data.table(df)

df[,"growth":=(wt-shift(wt,1))/age,by=.(squirrel)]

enter image description here