使用Dplyr使用约束汇总数据帧

时间:2018-04-10 19:19:43

标签: r if-statement dplyr mutate summarize

我的数据框类似于下面的数据框:

data <- data.frame(x = c("0", "2", "8", "1", "7", "10", "15", "14", "13", "11"),
                   y = c("11", "5", "14", "9", "13", "7", "4", "0", "12", "8"),
                   act_x = c("Short", "Buy", "Short", "Buy", "Short", "Buy", "Short", "Buy", "Short", "Buy"),
                   act_y = c("Buy", "Short", "Buy", "Short", "Buy", "Short", "Buy", "Short", "Buy", "Short"))

我希望根据x和y的操作为x创建一个利润列,为y创建一个利润列。结果应如下所示:

res <- data.frame(data,
                  prof_x = c(NA, -2, 6, 7, 6, -3, 5, 1, -1, 2),
                  prof_y = c(NA, -6, -9, -5, -4, -6, 3, -4, -12, -4))

例如,从第0天(第一行)开始,我卖空x并买y。相应的价格在第1天(第二行)移动并结算。 x的利润是0-2=-2(因为我缩短了x),y的利润是5-11=-6(因为我买了y)。等等...

在Dplyr管道中有没有友好的方法来实现它?有没有人在管道外面有任何建议?提前感谢任何指导。

1 个答案:

答案 0 :(得分:2)

使用dplyrlag的基于mutate的解决方案可以实现为:

library(dplyr)
data %>% mutate(x = as.numeric(x), y = as.numeric(y)) %>%
  mutate(prof_x = ifelse(act_x == "Buy", lag(x)-x, x-lag(x))) %>%
  mutate(prof_y = ifelse(act_y == "Buy", lag(y)-y, y-lag(y)))
# 
# x  y act_x act_y prof_x prof_y
# 1   0 11 Short   Buy     NA     NA
# 2   2  5   Buy Short     -2     -6
# 3   8 14 Short   Buy      6     -9
# 4   1  9   Buy Short      7     -5
# 5   7 13 Short   Buy      6     -4
# 6  10  7   Buy Short     -3     -6
# 7  15  4 Short   Buy      5      3
# 8  14  0   Buy Short      1     -4
# 9  13 12 Short   Buy     -1    -12
# 10 11  8   Buy Short      2     -4

数据:

data <- data.frame(x = c("0", "2", "8", "1", "7", "10", "15", "14", "13", "11"),
        y = c("11", "5", "14", "9", "13", "7", "4", "0", "12", "8"),
        act_x = c("Short", "Buy", "Short", "Buy", "Short", "Buy", "Short", "Buy", "Short", "Buy"),
        act_y = c("Buy", "Short", "Buy", "Short", "Buy", "Short", "Buy", "Short", "Buy", "Short"),
        stringsAsFactors = FALSE)