r - 基于多列过滤行,然后操作 R 中的另一列
问题描述
给定df
如下数据框:
df <- data.frame(city = c("bj", "bj", "bj", "bj", "sh", "sh", "sh", "sh", "sh" ),
type = c("a", "a", "b", "c", "a", "b", "c", "c", "a"),
count = c(100, 230, 12, 340, 17, 180, 25, 13, 12), stringsAsFactors = FALSE)
我想根据 city 和 type: 操作过滤器行bj-a, bj-c, sh-b
,然后将 count 的值除以10
:
预期的结果将是这样的:
city type count
bj a 10
bj a 23
bj b 12
bj c 34
sh a 17
sh b 18
sh c 25
sh c 13
sh a 12
我们怎么能在 R 中做到这一点?谢谢。
要过滤行,我们可以使用:
df %>%
filter(city == 'bj' & type %in% c('a', 'c') |
city == 'sh' & type == 'b')
解决方案
您可以使用ifelse
:
library(dplyr)
df %>%
mutate(count = ifelse(city == 'bj' & type %in% c('a', 'c') |
city == 'sh' & type == 'b', count/10, count))
这也可以在没有的情况下完成ifelse
:
df %>% mutate(count = count/c(1, 10)[(city == 'bj' & type %in% c('a', 'c') |
city == 'sh' & type == 'b') + 1])
推荐阅读
- jax-rs - Kumuluzee 微配置文件休息客户端 - 无法在错误响应中获取响应正文
- html - 我该如何搬家
在 ? - django - Django:获取点击按钮的ID
- c++ - c++ STL使用向量
调整大小失败 - python - 3-D 特征的 TFRecord 解析
- laravel - Laravel - 如何向 Laravel Spatie 权限添加额外的列
- mysql - SQL 保存已删除行的 PRIMARY KEY
- node.js - 对 passport.use(strategy) done 功能及其与 passport.authenticate 的关系感到困惑
- regex - 空字符串上的 Grep Perl 非贪婪范围正则表达式匹配问题
- python - 我如何将这个数据框中的可用兆瓦数量逐小时与价格范围相加到不同的列中?