【问题标题】:applying a function across rows in dataframe跨数据框中的行应用函数
【发布时间】:2021-06-18 14:26:32
【问题描述】:

我有一个包含 5 种鸟类大致数量的数据集。我编写了一个函数来使用 Broullions Index 计算物种的多样性。我的数据是这样的,我的函数是这样写的:

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,])

如何应用我的函数来计算跨行的 Broullions 指数?我认为像上面这样的东西会起作用,但还没有运气。关键是使用多样性指数作为与治疗 1 和 2 相关的响应变量,这就是为什么我想跨行求和并为每一行获取一个名为 bindex 的新变量的单个值。任何帮助将不胜感激。最好的,

【问题讨论】:

  • 感谢您的回复!我不习惯这样做,现在才学习 apply 的功能。第二个和第三个示例运行良好,但我确实在dplyr 中得到了解决方案的错误。错误提到 c_across() 只能在 dplyr 动词中使用。 (函数(cond)中的错误:在为函数“as.matrix”选择方法时评估参数“x”时出错:c_across() 只能在 dplyr 动词中使用。
  • 如果您使用的是旧版本的 dplyr,您能否显示packageVersion('dplyr'),它可能无法正常工作。谢谢。我用1.0.4

标签: r matrix apply rows


【解决方案1】:

我们可以使用rowwise进行分组

library(dplyr)
df <- df %>% 
  rowwise %>%
  mutate(bindex = Brillouin_Index(as.matrix(c_across(1:5)))) %>%
  ungroup

-输出

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)

【讨论】:

    猜你喜欢
    • 2022-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-04
    • 2023-04-01
    • 1970-01-01
    • 2021-09-24
    • 2014-05-07
    相关资源
    最近更新 更多