【问题标题】:Using summarise() to count the number of times the min value is repeated使用 summarise() 计算最小值重复的次数
【发布时间】:2021-04-13 21:07:27
【问题描述】:

我有这个 reach 数据框,其中包含有序值和可达性,我想要的输出是一个按集群分组 的几个属性的汇总表。整个表包含更多值,但我认为 10 行足以解释我想要实现的目标。

# A tibble: 500 x 3
  Order Reachability Cluster
   <int>        <dbl>   <dbl>
 1     1       NA           1
 2     2        1.54        1
 3     3        1.54        1
 4     4        0.860       1
 5     5        0.821       1
 6     6        0.821       1
 7     7        0.821       1
 8     8        0.821       1
 9     9        0.821       1
10    10        0.821       1
# ... with 490 more rows

我创建了一个汇总表,其中包含一些关于我的reach 表的位置信息。

reach %>% dplyr::group_by(Cluster) %>% 
    summarise(first_value = first(na.omit(Reachability)),
              min_value = min(na.omit(Reachability)),
              last_value = last(na.omit(Reachability)),
              first_pos = first(Order),
              min_pos = Order[which.min(Reachability)],
              last_pos = last(Order))

# A tibble: 1 x 7
  Cluster first_value min_value last_value first_pos min_pos last_pos
    <dbl>       <dbl>     <dbl>      <dbl>     <int>   <int>   <int>
1       1       1.54      0.821      0.821       1       5      10

我遇到的问题是 summarise 中的一个命令,它允许我计算“min_value”重复的次数。在这种情况下,对于0.821,“min_value”应该是 6。这是我尝试过的,但没有成功:

... %>% 
summarise(...
          ...
          N_min = sum(Reachability == min(na.omit(Reachability))))

... %>% 
summarise(...
          ...
          N_min = count(min(na.omit(Reachability))))

我错过了什么吗?我真的不知道为什么我的第一个选择不起作用。据我了解,如果我按小组进行计算,应该给我一个符合我条件的 TRUE(或 1)的总和。谢谢!

数据:

reach <- structure(list(Order = 1:10, Reachability = c(NA, 1.53995982068778, 
1.53995982068778, 0.860332791733694, 0.820585921380499, 0.820585921380499, 
0.820585921380499, 0.820585921380499, 0.820585921380499, 0.820585921380499
), Cluster = c(1, 1, 1, 1, 1, 1, 1, 1, 1, 1)), row.names = c(NA, 
-10L), class = c("tbl_df", "tbl", "data.frame"))

【问题讨论】:

  • 能否请您提供一个可重现的示例。
  • @Odysseus210 我的错!我添加了示例

标签: r dataframe count duplicates summarize


【解决方案1】:

理想情况下,您的第一个选项应该有效,但浮点比较再次不准确。 (参考Why are these numbers not equal?)

在使用sum之前尝试对数字进行四舍五入。

summarise(
  ...
  N_min = sum(round(Reachability, 2) == round(min(Reachability,na.rm = TRUE), 2))
  ...
)

【讨论】:

  • 我尝试对数字进行四舍五入,但似乎给了我相同的结果。由于某种原因,仍然存在 NA "N_min" 值
  • @ale.tenorio 在sum 中添加na.rm = TRUE 以忽略NA 值。 N_min = sum(round(Reachability, 2) == round(min(Reachability,na.rm = TRUE), 2), na.rm = TRUE)
猜你喜欢
  • 2019-01-29
  • 1970-01-01
  • 2020-12-23
  • 1970-01-01
  • 2015-08-31
  • 2016-05-12
  • 1970-01-01
  • 2014-04-28
  • 2018-06-15
相关资源
最近更新 更多