如何在R中按两列分组

编程入门 行业动态 更新时间:2024-10-15 20:17:26
本文介绍了如何在R中按两列分组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个数据框,我试图对其进行分组,然后根据两列进行求和.两列是字符,一个是月份,另一个是变量.

I have a data frame that I am trying to group and then sum based on two columns. The two columns are characters with one being month and the other variable.

以下是数据框架和结构的示例.

The following is a sample of the data frame and structure.

#row.names month variable amount 1 1-Jan x 1000 2 1-Jan x 3000 3 2-Feb z 5000 4 2-Feb y 3000

我尝试先对数据进行分组,然后尝试进行汇总,但是我无法让group_by_()完成此操作.下面是我尝试的代码.

I tried to group the data first and then I was going to try to summarise, however I am unable to get group_by_() to do the trick. Below is the code I tried.

byVarMonth <- group_by_(df, variable, (as.date(month)))

感谢您的帮助.

推荐答案

您显然对将角色[month]用作Date变量不感兴趣.考虑到我没错,您可以执行以下操作:

You apparently are not interested in taking your Character [month] as a Date variable. Considering that I'm not wrong you could simply do something like this:

library(dplyr) tab %>% group_by(month, variable) %>% summarise(a_sum=sum(amount), a_mean=(mean(amount)))

并得到这个:

Source: local data frame [3 x 4] Groups: month month variable a_sum a_mean 1 1-Jan x 4000 2000 2 2-Feb y 3000 3000 3 2-Feb z 5000 5000

更多推荐

如何在R中按两列分组

本文发布于:2023-11-22 14:26:20,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1617804.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何在   中按两列

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!