【问题标题】:R, How to filter dataframe based on bins and get the sum/counts for each column of unknown length?R,如何根据箱过滤数据帧并获取每列未知长度的总和/计数?
【发布时间】:2021-08-30 13:08:53
【问题描述】:

我有一个物种丰度数据框和几个环境变量,我已经将它们分箱并创建了一个“分箱列”。我正在努力获得每个垃圾箱中每个物种的丰度总和。我看到许多带有 tidyverse 的 R 示例,但似乎都使用了列的实际名称 - 我有几个数据框,其中一些包含数百个我不想输入的物种名称。

示例数据框:

head(data)  binned     Acanthamorpha    Belonidae   Blenoids
Site1_1       1           0               2           3
Site2_2       2           2               3           0
Site3_1       1           5               1           0
Site4_3       3           0               0           0
Site3_2       2           0               3           0

我稍后使用 bin 值标记站点名称,但实际上我想创建一个更小的数据框,如下所示:

bin    Acanthamorpha    Belonidae   Blenoids
 1          2               3          3
 2          4               6          0
 3          3               0          0

我对 tidyverses filter/mutate/groupby 感到困惑。

我玩过很多次,但似乎无法通过按 bin 值组织所有行:

data %>% filter(binned == 1) %>% gather(binned) %>% ???

但这里的错误也是调用每个值进行分箱。我确信有一种方法可以将数据框按垃圾箱分解,然后将每个物种的总和作为新行,然后将所有这些行(总共 5 行)保存为新数据框,但我无法得到它使用我的任何方法。

【问题讨论】:

  • 没有没有用。我还想保持行名完整,所以我尝试了rownames_to_columns('Sites') %>% group_by(binned %>% summarize(across(everything(),sum)) %>% columns_to_rownames('Sites'),但我收到错误Error: `across()` must only be used inside dplyr verbs.
  • 我也尝试过不将行名推送到列,以防万一导致错误但我得到了同样的错误。
  • 只是一个错字。问题依然存在。我接受了下面@Rory S 的回答。

标签: r


【解决方案1】:

这是你想要的吗?

library(tidyverse)

# Reproducing your data
df1 <- tibble(
  binned = c(1, 2, 1, 3, 2),
  Acanthamorpha = c(0, 2, 5, 0, 0),
  Belonidae = c(2, 3, 1, 0, 3),
  Blenoids = c(3, 0, 0, 0, 0)
)

df1 %>% 
  group_by(binned) %>%
  summarise_all(sum)

输出:

# A tibble: 3 x 4
  binned Acanthamorpha Belonidae Blenoids
   <dbl>         <dbl>     <dbl>    <dbl>
1      1             5         3        3
2      2             2         6        0
3      3             0         0        0

【讨论】:

  • 哇,是的,不敢相信我以前没有让 summarise_all 工作。我一直对特定列使用 summarise_all('column_name')。非常感谢!
猜你喜欢
  • 1970-01-01
  • 2020-04-22
  • 1970-01-01
  • 2015-04-19
  • 1970-01-01
  • 2011-08-28
  • 1970-01-01
  • 2020-12-10
  • 1970-01-01
相关资源
最近更新 更多