使用日期函数计算

问题描述 投票:0回答:2

需要获得这些年来每个月的销售额。

   Month    Sales
01-03-2018  2351
01-06-2018  4522
01-09-2018  3632
01-12-2018  6894
01-03-2019  5469
01-06-2019  6546
01-09-2019  7885
01-12-2019  6597
01-03-2020  7845
01-06-2020  6894
01-09-2020  5469
01-12-2020  6546
01-03-2021  2351
01-06-2021  4522
01-09-2021  3632
01-12-2021  6546
01-03-2022  7885
01-06-2022  6597
01-09-2022  7845
01-12-2022  6894

在这里,我想找到一年中每12个月的销售额。输出应如下:

Month   Sales
01-12-2018  6894
01-12-2019  6597
01-12-2020  6546
01-12-2021  6546
01-12-2022  6894

我可以从表格中选择每四行,但我想使用日期函数来完成。请帮忙。

r date lubridate
2个回答
2
投票

确保将列Month设置为日期变量并使用format获取月份,即

#Make sure it is a date variable
df$Month <- as.POSIXct(df$Month, format = '%d-%m-%Y')

df[format(df$Month, '%m') == 12,]

这使,

       Month Sales
4  2018-12-01  6894
8  2019-12-01  6597
12 2020-12-01  6546
16 2021-12-01  6546
20 2022-12-01  6894

1
投票

startsWith的一种方式:

#Month needs to be of character type
df[startsWith(df$Month, '01-12-'), ]
#        Month Sales
#4  01-12-2018  6894
#8  01-12-2019  6597
#12 01-12-2020  6546
#16 01-12-2021  6546
#20 01-12-2022  6894
© www.soinside.com 2019 - 2024. All rights reserved.