首页 > 解决方案 > 基于多列过滤行,然后操作 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')

标签: rdplyr

解决方案


您可以使用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])

推荐阅读