如何计算R

时间:2017-11-01 09:38:14

标签: r

我仍然是R的新手,并且我在现场测量的贻贝数据中包含以下数据框。我希望每个locID每天获得增长率(我有A1A2A3A4B1,{ {1}},B2B3B4C1C2C3C4,{{1 }},D1D2这样一个函数的循环理想情况下,但我现在只包括D3,分别用于10毫米贻贝和15毫米贻贝以及每个深度。因此,从第一个样本中获取每天的增长率将从D4C1)中减去11,0808-08-2017 39 1 C1 0,5 10 blue)的长度,并将其除以天9,9203-07-2017 3 1 C1 0,5 10 blue) - 3908-08-2017 39 1 C1 0,5 10 blue 11,08) 任何人都可以给我一些关于如何在3中找到计算方法的提示吗?我知道我问了很多,我希望有人愿意花时间帮忙!

提前谢谢!

03-07-2017  3   1   C1  0,5 10  blue        9,92

1 个答案:

答案 0 :(得分:1)

这就是你要追求的吗?

# sort the data (important)
df <- df[order(df$locID, df$depth, df$org_length, df$replica, df$n.), ]

# calculate rates
rates <- by(df, list(df$locID, df$depth, df$org_length, df$replica), function(x) {
  c(NA, diff(x$length)/diff(x$n.))})
rate_overall <- by(df, list(df$locID, df$depth, df$org_length, df$replica), function(x) {
  rep(diff(x$length[c(1, length(x$length))])/diff(x$n.[c(1, length(x$n.))]), nrow(x))})

# add rates to data
df$growth_rate <- unlist(rates)
df$overall_growth_rate <- unlist(rate_overall)

你得到了

> head(df)
          date n. session locID depth org_length replica length growth_rate overall_growth_rate
1   03-07-2017  3       1    C1   0.5         10    blue   9.92         NA        0.0145454545
33  08-08-2017 39       1    C1   0.5         10    blue  11.08 0.03222222        0.0145454545
81  05-09-2017 67       1    C1   0.5         10    blue  11.08 0.00000000        0.0145454545
113 29-09-2017 91       1    C1   0.5         10    blue  11.20 0.00500000        0.0145454545
5   03-07-2017  3       1    C1   0.5         10   green   9.89         NA        0.0294318182
37  08-08-2017 39       1    C1   0.5         10   green  10.91 0.07277778        0.0294318182