首页 > 解决方案 > 如何使用某些数据为组查找新列?

问题描述

我有家庭作为一个群体。在每个家庭中,每个成员都有一些数据。我需要找到乘公共汽车旅行的会员的旅行费用。通行证 30 天的票价是 84 美元,所以每天是 2.8 美元,学生和 60 岁以上的人的这个费用是一半。由于每次旅行是无限的,我想按每个人的旅行次数潜水 2.8。如果一个人没有乘公共汽车旅行,它是零。

这是一个例子:

     household     person      trip       mode       student     age
         1            1          1          car         1         23
         1            1          2           bus        1         23
         1            1          3           bus        1         23
         1            2          1          car         0         65
         1            2          2           walk       0         65
         1            2          3           bus        0         65
         2            1          1            bus       0         18
         2            1          2            bus       0         18
         2            2          1             walk     0          40

输出

      household     person      trip       mode       student     age   Fare
         1            1          1          car         1         23    1.4/2
         1            1          2           bus        1         23   1.4/2
         1            1          3           bus        1         23   1.4/2
         1            2          1          car         0         65   1.4/1
         1            2          2           walk       0         65   1.4/1
         1            2          3           bus        0         65   1.4/1
         2            1          1            bus       0         18   2.8/2
         2            1          2            bus       0         18   2.8/2
         2            2          1             walk     0          40   0

第一个人是学生,有 2 趟巴士,所以费用是 1.4/2,第二个人有 1 趟巴士,年龄超过 65 岁。在第二个家庭中,第一个人有 2 次公共汽车旅行,但他是阳人而不是学生,所以成本是 2.8/2 最后一个人没有公共汽车旅行,所以 0。

标签: rdataframe

解决方案


这是使用dplyr. 我们将数据框分组householdperson如果此人是studentOR,age > 60我们应用一半rate并将其除以次数mode == "bus"

rate = 2.8
library(dplyr)

df %>%
  group_by(household, person) %>%
  mutate(Fare = case_when(any(student == 1 | age > 60) & any(mode == "bus") ~ 
                         (rate/2)/sum(mode == "bus"), 
                      any(mode == "bus") ~ rate/sum(mode == "bus"), 
                      TRUE ~ 0))

# household person  trip mode  student   age  Fare
#      <int>  <int> <int> <fct>   <int> <int> <dbl>
#1         1      1     1 car         1    23   0.7
#2         1      1     2 bus         1    23   0.7
#3         1      1     3 bus         1    23   0.7
#4         1      2     1 car         0    65   1.4
#5         1      2     2 walk        0    65   1.4
#6         1      2     3 bus         0    65   1.4
#7         2      1     1 bus         0    18   1.4
#8         2      1     2 bus         0    18   1.4
#9         2      2     1 walk        0    40     0  

推荐阅读