0

I am trying to extract the names of the countries which don't start with either "C" or "B" from this vector.

vec <- c("Colombia", "Chile", "Brazil", "Ecuador", "Peru", "Mexico")

This works for C or B only:

vec[substring(vec,1,1) != 'C']

I am trying to combine both cases but this doesn't work

vec[(substring(vec,1,1) != 'C') | (substring(vec,1,1) != 'P')]

How can I combine both conditions in just one statement?

applicant
  • 105
  • 2
  • Shouldn't it be `&` instead of `|`? `vec[(substring(vec,1,1) != 'C') & (substring(vec,1,1) != 'P')]` – Z.Lin Sep 14 '17 at 02:25
  • Something using regular expressions would be neater though. See [here](https://stackoverflow.com/questions/8438173/r-regex-match-strings-not-beginning-with-a-pattern) for ideas. – Z.Lin Sep 14 '17 at 02:31

2 Answers2

2

Isn't this what you are looking for?

vec[!substring(vec, 1, 1) %in% c("B", "C")]
Kevin Arseneau
  • 6,186
  • 1
  • 21
  • 40
1

You can use grep for this:

vec[grep("^[^CP]",vec)]
Jul
  • 1,129
  • 6
  • 12
  • 1
    You can also use `value = TRUE` so you don't even have to subset: `grep('^[^CP]', vec, value = TRUE)` – alistaire Sep 14 '17 at 02:39