我有一个数据框,其中每一行代表一个具有物种数量和个体数量的群落:
n.species<- c(3,5,10,15,20)
n.indiv <- c(30, 40, 50, 100, 200, 300, 500, 750, 1000)
n.indiv <- rep(n.indiv, each = length(S))
df <- data.frame(S = rep(S, length(n.indiv) / length(S)), n.indiv)
df$margalef <- (df$n.species-1)/(log(df$n.indiv))
print(df)
我想计算每行的 margalef (df$n.species-1)/(log(df$n.indiv)) 对 n.indiv 的积分。
我该怎么做?
提前致谢
您可以使用以下函数(以数值方式)计算积分:
trapint<-function (x, y, a, b)
{
if (length(x) != length(y))
stop("length x must equal length y")
y <- y[x >= a & x <= b]
x <- x[x >= a & x <= b]
if (length(unique(x)) < 2)
return(NA)
ya <- approx(x, y, a, ties = max, rule = 2)$y
yb <- approx(x, y, b, ties = max, rule = 2)$y
x <- c(a, x, b)
y <- c(ya, y, yb)
h <- diff(x)
lx <- length(x)
result<-0.5 * sum(h * (y[-1] + y[-lx]))
return(result)
}
参数为:
x: the x values of your graph
y: the y values of your graph
a: lower integral border (from where to start integrating)
b: upper integral border (where to end integration)
xvalues<- -10:10
yvalues<- -xvalues^2
# Integrate from 0 to 5
trapint(x=xvalues,y=yvalues,a=0,b=5)
## Result: -42.5
请注意,这是积分的近似值,并且很大程度上取决于图形的分辨率! 将其与此处的“真实”解决方案进行比较:https://www.wolframalpha.com/input?i=Integral+of+y%3D-x%5E2+from+0+to+5