r - 如何使用某些数据为组查找新列?
问题描述
我有家庭作为一个群体。在每个家庭中,每个成员都有一些数据。我需要找到乘公共汽车旅行的会员的旅行费用。通行证 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。
解决方案
这是使用dplyr
. 我们将数据框分组household
,person
如果此人是student
OR,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
推荐阅读
- angular - 从 Angular 10 访问时在 Hasura Graphql 上遇到 CORS 问题
- linux - 只有一组 shell 脚本应该执行一个 shell 脚本
- java - 房间数据库中更新的重复数据条目
- laravel - laravel 电子邮件验证 mailtrap 在 localhost 上有效,但在 ubuntu 服务器 digitalocean 上无效
- r - 从 R 中的递归函数编译向量
- php - 在 Symfony 3.4 中找不到模板错误
- python - 为什么我不能在 heroku 上部署 react flask 应用程序?
- slack-api - 如何更改 Slack 中的模态图标?
- python - 在 pandas 数据框中查找事件的每个 id 的连续天数
- javascript - 在 useState 中更新 Map 时避免重新渲染组件