Reputation: 60
I need to replace multiple elements with NAs.
This is my data:
data<-c("?","acaova","acapin","agrsto","alsaur","alsaurM","apeintM","arichi", "artabs","auschi","auschiM","auspen","berdar","berser","bertri","brocat", "brocol","brocolM","calpol","carand","cartho","cerarv","chucol","chucolM", "cirvul","claper","colbif","colbifM","colhys","corsel","corseo","crecap", "crecapM","cynech","d","d3","dacglo","diojun","diojunM","dipdes", "dros","elyang","elyangM","epibra","equbog","erocic","erocicM","erypan", "g","galapa","galhyp","ganu","ganuM","gaupoe","gerses","gM", "gper","gperM","h1","h1M","h2","hd3","hd5","hollan", "hydcha","hyppoe","hyprad","hypradM","leuvul","lotten","luppolM","nas", "nasM","naspoe","notant","notantM","papspe","plalan","plalanM","poapra", "poapraM","poasec","poasecM","potchi","pruavi","pruvul","ribcuc","rosrub", "rosrubM","rosrubP","schpat","schpatP","sdjab","senfil","solchi","t10h3", "t10h4","t10h6","t10h7","t10h8","t10h9","t2h8","tarofi","tr,notant" "tripra","tripraM","trirep","urture","usnbar","vertha","vicnig")
And I need to replace many elements with NAs. The only way I found to do it was with this code:
data[data=="b"]<-NA
data[data=="r"]<-NA
data[data=="ro"]<-NA
data[data=="sd"]<-NA
data[data=="t"]<-NA
data[data=="tr"]<-NA
Is there a simpler way?
Upvotes: 1
Views: 33
Reputation: 521249
You could use grepl
along with a regex alternation:
terms <- c("b", "r", "ro", "sd", "t", "tr")
regex <- paste0("^(?:", paste(terms, collapse="|"), ")")
data[grepl(regex, data)] <- NA
data
[1] "?" "acaova" "acapin" "agrsto" "alsaur" "alsaurM" "apeintM"
[8] "arichi" "artabs" "auschi" "auschiM" "auspen" NA NA
[15] NA NA NA NA "calpol" "carand" "cartho"
[22] "cerarv" "chucol" "chucolM" "cirvul" "claper" "colbif" "colbifM"
[29] "colhys" "corsel" "corseo" "crecap" "crecapM" "cynech" "d"
[36] "d3" "dacglo" "diojun" "diojunM" "dipdes" "dros" "elyang"
[43] "elyangM" "epibra" "equbog" "erocic" "erocicM" "erypan" "g"
[50] "galapa" "galhyp" "ganu" "ganuM" "gaupoe" "gerses" "gM"
[57] "gper" "gperM" "h1" "h1M" "h2" "hd3" "hd5"
[64] "hollan" "hydcha" "hyppoe" "hyprad" "hypradM" "leuvul" "lotten"
[71] "luppolM" "nas" "nasM" "naspoe" "notant" "notantM" "papspe"
[78] "plalan" "plalanM" "poapra" "poapraM" "poasec" "poasecM" "potchi"
[85] "pruavi" "pruvul" NA NA NA NA "schpat"
[92] "schpatP" NA "senfil" "solchi" NA NA NA
[99] NA NA NA NA NA NA "notant"
[106] NA NA NA "urture" "usnbar" "vertha" "vicnig"
Upvotes: 2