管道语句中的舍入向量仅产生向量中的第一个元素

时间:2019-03-06 16:02:53

标签: r dplyr

我有一个小标题,已按组进行汇总,希望将最大平均值和最小平均值提取到2元素向量中。

我还需要确定最大值和最小值之间的差是否小于等于1,然后需要将向量四舍五入为3位数字,如果不是,则可以四舍五入为整数。

由于某种原因,当我在管道语句中执行此操作时,它仅返回四舍五入的第一个元素。是什么导致这种行为?

library(tidyverse)

set.seed(123)

tibble(x = runif(30, min = 205, max = 1440),
       y = rep(paste0("Group",1:5), each = 6)) %>% 
  group_by(y) %>% 
  summarize(mean = mean(x)) %>% 
  {c(min(.$mean), max(.$mean))} %>% 
  {ifelse(diff(.) <= 1, round(., digits = 2), round(., digits = 0))}
#> [1] 728

# Expected Behavior
c(728.0433, 1131.1561) %>% 
  round(digits = 0)
#> [1]  728 1131

1 个答案:

答案 0 :(得分:0)

您可以执行以下任一操作:

tibble(x = runif(30, min = 205, max = 1440),
       y = rep(paste0("Group",1:5), each = 6)) %>% 
  group_by(y) %>% 
  summarize(mean = mean(x)) %>% 
  {c(min(.$mean), max(.$mean))} %>% 
  {ifelse(rep(diff(.) <= 1, 2), round(., digits = 2), round(., digits = 0))}

tibble(x = runif(30, min = 205, max = 1440),
       y = rep(paste0("Group",1:5), each = 6)) %>% 
  group_by(y) %>% 
  summarize(mean = mean(x)) %>% 
  {c(min(.$mean), max(.$mean))} %>% 
  {if(diff(.) <= 1) round(., digits = 2) else round(., digits = 0)}