我有一个5种鸟类的大致计数的数据集。我写了一个函数,用布鲁利指数计算物种的多样性。我的数据是这样的,我的函数是这样写的:
df <- data.frame(
sp1 = c(2, 3, 4, 5),
sp2 = c(1, 6, 7, 2),
sp3 = c(1, 9, 4, 3),
sp4 = c(2, 2, 2, 4),
sp5 = c(3, 3, 2, 1),
treatment1 = c("A", "B", "C", "A"),
treatment2 = c("D", "E", "D", "E")
)
#write function that estimates Broullion's Index
Brillouin_Index <- function(x){
N <- sum(x)
(log10(factorial(N)) - sum(log10(factorial(x)))) / N
}
df2 <- df %>%
mutate(bindex = Brillon_Index(matrix(df[1:5,])如何应用我的函数来计算各行的布鲁利奥斯指数?我以为像上面这样的东西会起作用,但还没有运气。重点是使用多样性指数作为与处理1和2相关的响应变量,这就是为什么我希望对各行求和,并为名为bindex的新变量获得每行的单个值。任何帮助都将不胜感激。最好的
发布于 2021-03-22 05:19:50
我们可以使用rowwise按行分组
library(dplyr)
df <- df %>%
rowwise %>%
mutate(bindex = Brillouin_Index(as.matrix(c_across(1:5)))) %>%
ungroup-output
df
# A tibble: 4 x 8
# sp1 sp2 sp3 sp4 sp5 treatment1 treatment2 bindex
# <dbl> <dbl> <dbl> <dbl> <dbl> <chr> <chr> <dbl>
#1 2 1 1 2 3 A D 0.464
#2 3 6 9 2 3 B E 0.528
#3 4 7 4 2 2 C D 0.527
#4 5 2 3 4 1 A E 0.505或者在base R中使用apply
df$bindex <- apply(df[1:5], 1, Brillouin_Index)
df$bindex
#[1] 0.4643946 0.5277420 0.5273780 0.5051951或者在collapse中使用dapply
library(collapse
df$bindex <- dapply(slt(df, 1:4), Brillouin_Index, MARGIN = 1)https://stackoverflow.com/questions/66737644
复制相似问题