将同一组内的观测值之间的差异与参考观测值进行比较

时间:2018-10-02 04:31:38

标签: r dplyr

test <- data.frame('prod_id'= c("shoe", "shoe", "shoe", "shoe", "shoe", "shoe", "boat", "boat","boat","boat","boat","boat"), 
               'seller_id'= c("a", "b", "c", "d", "e", "f", "a","g", "h", "r", "q", "b"), 
               'Dich'= c(1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0),
               'price' = c(120, 20, 10, 4, 3, 4, 30, 43, 56, 88, 75, 44)
                )
test

       prod_id seller_id Dich price
 1     shoe         a    1   120
 2     shoe         b    0    20
 3     shoe         c    0    10
 4     shoe         d    0     4
 5     shoe         e    0     3
 6     shoe         f    0     4
 7     boat         a    0    30
 8     boat         g    0    43
 9     boat         h    1    56
10     boat         r    0    88
11     boat         q    0    75
12     boat         b    0    44

因此,我想创建一个新列,该列基于Dich的值获取价格列中观察值之间的差异,其中每个观察值与每个prod_id组中Dich == 1的观察值之间的差异。

这是我下面想要的结果。

       prod_id seller_id Dich price diff_p
 1     shoe         a    1   120      0
 2     shoe         b    0    20     -100
 3     shoe         c    0    10     -110
 4     shoe         d    0     4     -116
 5     shoe         e    0     3     -117
 6     shoe         f    0     4     -116
 7     boat         a    0    30     -26
 8     boat         g    0    43     -13
 9     boat         h    1    56       0
10     boat         r    0    88      32
11     boat         q    0    75      19
12     boat         b    0    44     -12

1 个答案:

答案 0 :(得分:1)

按“ prod_id”分组后,取“ Dich”为1的“ price”和“ price”之差

library(dplyr)
test %>% 
    group_by(prod_id) %>%
    mutate(diff_p = price - price[Dich == 1])
# A tibble: 12 x 5
# Groups:   prod_id [2]
#   prod_id seller_id  Dich price diff_p
#   <fct>   <fct>     <dbl> <dbl>  <dbl>
# 1 shoe    a             1   120      0
# 2 shoe    b             0    20   -100
# 3 shoe    c             0    10   -110
# 4 shoe    d             0     4   -116
# 5 shoe    e             0     3   -117
# 6 shoe    f             0     4   -116
# 7 boat    a             0    30    -26
# 8 boat    g             0    43    -13
# 9 boat    h             1    56      0
#10 boat    r             0    88     32
#11 boat    q             0    75     19
#12 boat    b             0    44    -12

或使用data.table

library(data.table)
setDT(test)[, diff_p := price - price[Dich == 1], prod_id]