I've created a little example which I hope helps.
Some things to consider:
The left hand side of the argument in case_when()
needs to be a logical statement (i.e. TRUE
or FALSE
result). The str_subset()
function you used returns strings that match your condition, not logical. In my below example I use str_starts()
which returns a logical which matches the condition of your input.
NULL values are ignored in case_when()
, but you can also specify what to do with them if you prefer. Check out the documentation ?case_when
for an example of this.
Good luck and welcome to R!
library(dplyr)
#>
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#>
#> filter, lag
#> The following objects are masked from 'package:base':
#>
#> intersect, setdiff, setequal, union
library(stringr)
# create data frame with countries, include NA for demonstration
df <- tibble(
country = c("Columbia", "Uruguay", "Argentina", "Brazil", NA)
)
df2 <-
df %>%
mutate(
starts_vowel =
case_when(
# left hand side of case_when must be a logical
str_starts(country, "A|E|I|O|U") ~ 1,
#Adding negate = TRUE returns non-matching
str_starts(country, "A|E|I|O|U", negate = TRUE) ~ 0,
)
)
df2
#> # A tibble: 5 x 2
#> country starts_vowel
#> <chr> <dbl>
#> 1 Columbia 0
#> 2 Uruguay 1
#> 3 Argentina 1
#> 4 Brazil 0
#> 5 <NA> NA
# Check out the difference between str_subset and #str_starts
str_subset(df$country, "^[A|E|I|O|U]")
#> [1] "Uruguay" "Argentina"
str_starts(df$country, "A|E|I|O|U")
#> [1] FALSE TRUE TRUE FALSE NA
Created on 2020-02-24 by the reprex package (v0.3.0)