我有一个数据集,如下所示:
time type amount
1 2017/1/1 0:00 income 729.64
2 2017/1/1 0:05 income 1465.15
3 2017/1/1 0:10 outcome 1456.07
4 2017/1/1 0:15 outcome 1764.28
...
289 2017/1/2 0:00 income 719.64
290 2017/1/2 0:05 income 165.15
291 2017/1/2 0:10 income 1006.07
292 2017/1/2 0:15 outcome 104.28
我想按日期计算净收入,如果您的收入超过结果,结果将为正,否则为负。 结果应该如下所示:
date netincome
1 2017/1/1 -729.64
2 2017/1/2 1465.15
3 2017/1/3 1456.07
4 2017/1/4 1764.28
...
我怎样才能有效地得到这个?
最佳答案
示例数据:
df <- data.frame(time=c("2017/1/1 0:00", "2017/1/1 0:05", "2017/1/1 0:10","2017/1/2 0:00", "2017/1/2 0:05", "2017/1/2 0:10"),
type=c("income", "income", "outcome", "income", "outcome", "outcome"),
amount=c(729.64, 1465.15, 1456.07, 729.64, 729.64, 1456.07))
将时间
转换为日期
并将结果
转换为负值:
df$date <- lubridate::date(df$time)
df$amount[df$type=="outcome"] <- df$amount[df$type=="outcome"]*-1
使用dplyr
汇总数据(按日期
计算amount
的总和):
library(dplyr)
output <- df %>% group_by(date) %>% summarise(netincome=sum(amount))
结果:
output
# A tibble: 2 x 2
date netincome
<chr> <dbl>
1 2017/1/1 738.72
2 2017/1/2 -1456.07
关于r - 计算净利润,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48983204/