Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/redis/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 根据月份对行子集执行函数?_R - Fatal编程技术网

R 根据月份对行子集执行函数?

R 根据月份对行子集执行函数?,r,R,我有这样一个数据集: Company Month Price Quantity A 1/1/2014 46 4788 B 1/1/2014 43 6242 C 1/1/2014 50 5432 D 1/1/2014 26 4153 A 2/1/2014 21 5301 B 2/1/2014 46 2706 C 2/1/2014 33 9803 D 2/1/2014 42 9208 A 3/

我有这样一个数据集:

Company Month   Price   Quantity
A   1/1/2014    46  4788
B   1/1/2014    43  6242
C   1/1/2014    50  5432
D   1/1/2014    26  4153
A   2/1/2014    21  5301
B   2/1/2014    46  2706
C   2/1/2014    33  9803
D   2/1/2014    42  9208
A   3/1/2014    45  6309
B   3/1/2014    30  9457
C   3/1/2014    20  6050
D   3/1/2014    16  3151
Month   Result
1/1/2014    868232
2/1/2014    946032
3/1/2014    739031
我正在尝试执行一个简单的函数
sum(price*quantity)
,该函数在数据集中每个月求和,并将结果发送到新的数据帧

结果如下所示:

Company Month   Price   Quantity
A   1/1/2014    46  4788
B   1/1/2014    43  6242
C   1/1/2014    50  5432
D   1/1/2014    26  4153
A   2/1/2014    21  5301
B   2/1/2014    46  2706
C   2/1/2014    33  9803
D   2/1/2014    42  9208
A   3/1/2014    45  6309
B   3/1/2014    30  9457
C   3/1/2014    20  6050
D   3/1/2014    16  3151
Month   Result
1/1/2014    868232
2/1/2014    946032
3/1/2014    739031

我已经尝试了
aggregate()
函数,但是运气不好。这是否像
subset()函数那样简单?提前感谢您的帮助。

按“月”分组后,得到“价格”、“数量”和
总和的乘积
it

library(dplyr)
df1 %>%
  group_by(Month) %>% 
  summarise(Result = sum(Price*Quantity))
# A tibble: 3 x 2
#  Month    Result
#  <chr>     <int>
#1 1/1/2014 868232
#2 2/1/2014 946032
#3 3/1/2014 739031

dplyr
lubridate
软件包允许您按月分组,然后总结:

library(dplyr)
library(lubridate)
sum_monthly <- df %>% 
  mutate(Month = mdy(Month)) %>% # Converting month to date format
  group_by(month(Month)) %>% 
  summarise(Result = sum(Quantity * Price))
库(dplyr)
图书馆(lubridate)
每月金额%
mutate(Month=mdy(Month))%>%#将月份转换为日期格式
分组单位(月)(月))%>%
总结(结果=总和(数量*价格))

非常感谢!这个聚合建议非常巧妙。快速提问:现在,当我在一个包含三年数据的数据集上运行聚合函数时,我会得到一个非时间顺序的月度结果列。(即2014年1月1日、2015年1月1日、2016年1月1日,而不是2014年1月1日、2014年2月1日、2014年3月1日)您对该列排序的建议是什么?是否可以在聚合函数中执行此操作?再次感谢。@R.Baratheon这是因为列是
字符
因子
类。您可能需要转换为
Date
类,即
聚合(cbind(结果=价格*数量)~月,转换(df1,月=as.Date(月,“%m/%d/%Y”)),FUN=sum)
@R.Baratheon同样,如果每个月有许多天,我们需要转换为
月-年
聚合(cbind(结果=价格*数量)~Month,transform(df1,Month=zoo::as.yearmon(Month,“%m/%d/%Y”)),FUN=sum)