r - 计算净利润

标签 r dataframe dplyr

我有一个数据集,如下所示:

            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/

相关文章:

r - 如何滞后 dplyr 中的同一列?

r - dplyr 习语用于 summarize() 过滤分组依据,并且还替换由于缺少行而导致的任何 NA

r - 如何在 Shiny 中从 server.R 解析为 HTML 标签

python - Pandas 数据帧 : converting integer to hh:mm

python - 下载数据并附加到不同的数据框

python - Pandas 日期时间格式不一致

r - dplyr 过滤器仅获取其中一组采用的值

R 相当于 Java 映射

r - 列出顾客访问日并总结他们在 R 中的滞后天数

r - 根据整数值查找表