【问题标题】:How does one summarize with conditions into a single variable in R?如何将条件汇总为 R 中的单个变量?
【发布时间】:2018-03-27 11:09:11
【问题描述】:

我想在分组数据后使用来自 dplyr 的summarise() 来计算一个新变量。但是,我希望它对一些数据使用一个方程,对其余数据使用第二个方程。

我尝试过将group_by()summarise()if_else() 一起使用,但它不起作用。

这是一个例子。假设——出于某种原因——我想为萼片长度找到一个特殊的值。对于“setosa”物种,这个特殊值是萼片长度平均值的两倍。对于所有其他物种,它只是萼片长度的平均值。这是我尝试过的代码,但它不适用于summarise()

library(dplyr)
iris %>%
   group_by(Species) %>%
   summarise(sepal_special = if_else(Species == "setosa", mean(Sepal.Length)*2, mean(Sepal.Length)))

这个想法适用于mutate(),但我需要重新格式化 tibble 以成为我正在寻找的数据集。

library(dplyr)
iris %>%
   group_by(Species) %>%
   mutate(sepal_special = if_else(Species == "setosa", mean(Sepal.Length)*2, mean(Sepal.Length)))

这就是我希望生成的 tibble 的布局方式:

library(dplyr)
iris %>%
group_by(Species)%>%
summarise(sepal_mean = mean(Sepal.Length))

  # A tibble: 3 x 2
  # Species    sepal_special
  # <fctr>          <dbl>
  #1 setosa           5.01
  #2 versicolor       5.94
  #3 virginica        6.59
  #> 

但我的结果会显示 setosa x 2 的值

# A tibble: 3 x 2
      # Species    sepal_special
      # <fctr>          <dbl>
      #1 setosa          **10.02**
      #2 versicolor       5.94
      #3 virginica        6.59
      #> 

建议?我觉得我真的在寻找将if_else()summarise() 结合使用的方法,但在任何地方都找不到,这意味着一定有更好的方法。

谢谢!

【问题讨论】:

  • 只需将初始尝试中的Species == "setosa" 更改为Species[1] == "setosa"

标签: r dplyr


【解决方案1】:

mutate 步骤之后,使用summarise 为每个“物种”获取“sepal_special”的first 元素

iris %>% 
  group_by(Species) %>% 
  mutate(sepal_special = if_else(Species == "setosa", 
               mean(Sepal.Length)*2, mean(Sepal.Length))) %>% 
 summarise(sepal_special = first(sepal_special))
# A tibble: 3 x 2
#  Species    sepal_special
#   <fctr>             <dbl>
#1 setosa             10.0 
#2 versicolor          5.94
#3 virginica           6.59

或者不是调用mutate,而是在应用if_else之后,获取summarise中的第一个值

iris %>% 
   group_by(Species) %>%
   summarise(sepal_special = if_else(Species == "setosa", 
           mean(Sepal.Length)*2, mean(Sepal.Length))[1]) 
# A tibble: 3 x 2
#  Species    sepal_special
#  <fctr>             <dbl>
#1 setosa             10.0 
#2 versicolor          5.94
#3 virginica           6.59

【讨论】:

  • 谢谢!!!这是一个。我喜欢在summarise 之后取第一个值的答案。有时,当我不想完成此报告时,我将不得不深入研究为什么 if_else 声明需要这样做,而 summarise 则不需要。非常感谢!
【解决方案2】:

另一种选择:由于两次平均值与两次值的平均值相同,您可以将 setosa 的萼片长度加倍,然后总结:

iris %>% 
  mutate(Sepal.Length = ifelse(Species == "setosa", 2*Sepal.Length, Sepal.Length)) %>% 
  group_by(Species) %>% 
  summarise(sepal_special = mean(Sepal.Length))

# A tibble: 3 x 2
  Species    sepal_special
  <fct>              <dbl>
1 setosa             10.0 
2 versicolor          5.94
3 virginica           6.59

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-02-08
    • 1970-01-01
    • 2020-11-27
    • 2022-07-12
    • 1970-01-01
    • 1970-01-01
    • 2021-09-05
    相关资源
    最近更新 更多