如何使用dplyr根据向量中字符串的存在来突变和分配值

时间:2019-02-20 09:22:01

标签: r dplyr

我有以下数据框:

library(tidyverse)
dat <- mtcars %>% 
  rownames_to_column(var = 'car_name') %>% 
  as.tibble() %>% 
  head(n=5) %>% 
  select(car_name, mpg)

dat
#> # A tibble: 32 x 2
#>    car_name            mpg
#>    <chr>             <dbl>
#>  1 Mazda RX4          21  
#>  2 Mazda RX4 Wag      21  
#>  3 Datsun 710         22.8
#>  4 Hornet 4 Drive     21.4
#>  5 Hornet Sportabout  18.7

reprex package(v0.2.0)于2019-02-20创建。

给出一个向量:

good_cars <- c("Mazda RX4", "Mazda RX4 Wag", "Datsun 710")

我想分配在dat中添加另一列,这样每当car_name存储在good_cars中时,我都会将状态分配为好:

我尝试过但是失败了:

dat %>% 
 mutate(condition = case_when( car_name %in% good_cars == "GOOD" ~ "BAD"))

我想要得到的结果是:

  car_name            mpg condition
  <chr>             <dbl> <chr>    
1 Mazda RX4          21   GOOD      
2 Mazda RX4 Wag      21   GOOD       
3 Datsun 710         22.8 GOOD       
4 Hornet 4 Drive     21.4 BAD      
5 Hornet Sportabout  18.7 BAD

1 个答案:

答案 0 :(得分:1)

library(tidyverse)
dat <- mtcars %>% 
  rownames_to_column(var = 'car_name') %>% 
  as.tibble() %>% 
  head(n=5) %>% 
  select(car_name, mpg)

dat%>%mutate(condition=if_else(car_name%in%good_cars,"GOOD","BAD"))
# A tibble: 5 x 3
  car_name            mpg condition
  <chr>             <dbl> <chr>    
1 Mazda RX4          21   GOOD     
2 Mazda RX4 Wag      21   GOOD     
3 Datsun 710         22.8 GOOD     
4 Hornet 4 Drive     21.4 BAD      
5 Hornet Sportabout  18.7 BAD