组或总和更多列

发布于 2025-01-27 11:23:07 字数 383 浏览 2 评论 0原文

我想知道是否存在同一时间的“自动”方法“自动”。

library(dplyr)
abc <- iris %>% 
      group_by(Species) %>% 
      summarise(abc = sum(Petal.Width)) %>% 
      ungroup() 
abc2 <- iris %>% 
      group_by(Species) %>% 
      summarise(abc = sum(Sepal.Width)) %>% 
      ungroup() 

我可以为每列使用此代码,但是如果我需要做更多的列(在此数据集中,前四个),我该怎么办?而且我需要在同一数据集中,这是可能的吗?

I would like to know if exist a method "automatic" for calculted more column in the same time.

library(dplyr)
abc <- iris %>% 
      group_by(Species) %>% 
      summarise(abc = sum(Petal.Width)) %>% 
      ungroup() 
abc2 <- iris %>% 
      group_by(Species) %>% 
      summarise(abc = sum(Sepal.Width)) %>% 
      ungroup() 

I can use this code for each column but if i need to do more column (in this dataset the first four), how can I do? And I need in the same dataset, it is possible?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

失而复得 2025-02-03 11:23:07

尝试以下操作:

iris %>% 
  group_by(Species) %>% 
  summarise(across(Sepal.Length:Petal.Width, sum))


# A tibble: 3 x 5
  Species    Sepal.Length Sepal.Width Petal.Length Petal.Width
  <fct>             <dbl>       <dbl>        <dbl>       <dbl>
1 setosa             250.        171.         73.1        12.3
2 versicolor         297.        138.        213          66.3
3 virginica          329.        149.        278.        101. 

Try this:

iris %>% 
  group_by(Species) %>% 
  summarise(across(Sepal.Length:Petal.Width, sum))


# A tibble: 3 x 5
  Species    Sepal.Length Sepal.Width Petal.Length Petal.Width
  <fct>             <dbl>       <dbl>        <dbl>       <dbl>
1 setosa             250.        171.         73.1        12.3
2 versicolor         297.        138.        213          66.3
3 virginica          329.        149.        278.        101. 
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文