Subset specific rows in a dataframe, but keeping the observations

Viewed 31

I have a dataframe which look like this

y = data.frame(subdel = c(1, 2, 3, 1, 57, 14, 1, 2, 57, 57, 57, 3, 1, 1, 
  31, 21, 34, 56, 12, 45, 1, 63, 31, 34), muni =  c("A01",  "A83", "A40", NA, NA, NA, NA, NA, NA, NA, NA,  "A45", "B26", "B42","B61", "B70", "B90", "C53", "C89","A45", "B26", "B42","B61", "B70"))

I'm expecting the next result:

z = data.frame(subdel = c(1, 2, 3, 57, 57, 57, 57, 3, 1, 1, 31, 21, 34, 56, 12, 45, 1, 63, 31, 34), muni =  c("A01",  "A83", "A40", NA, NA, NA, NA,  "A45", "B26", "B42","B61", "B70", "B90", "C53", "C89", "A45", "B26", "B42","B61", "B70"))

I want to match subdel == 57 with muni == NA, but, as you can see, conservating all the another observations in the dataframe.

Any help would be appreciated.

1 Answers

We can use subset with a logical condition i.e. check for NA in 'muni' (is.na(muni)) and (&) where the 'subdel' is 57 (subdel == 57) or all other non-NA elements from 'muni' (!is.na(muni))

subset(y, is.na(muni) & subdel == 57 | !is.na(muni))
Related