Take the 2-minute tour ×

I have a csv file with 1 column, Address. It has values like:

A <- structure(list(Address = structure(1:3, .Label = c("&2340 P St", 
 "&5656 N St", "456 B Street"), class = "factor")), .Names = "Address", 
 row.names = c(NA, 3L), class = "data.frame")
##        Address
## 1   &2340 P St
## 2   &5656 N St
## 3 456 B Street

I need to clean data – to erase all characters (or replace with space) if there is “&”. I am expecting this result in my 2.csv file:

##        Address
## 1 456 B Street

Here's the code:

 A <-read.csv("U:/161/1.csv", header=T,sep=",")
 B<-gsub("&", " ", A$ADDRESS1, ignore.case = TRUE)
 write.table(B, file = "U:/161/2.csv", sep = ","
 , col.names = NA, qmethod = "double")

It only removes “&”. How do I remove the rest of address?

share|improve this question
What is the rest of the adress you want removed? –  Tyler Rinker Oct 16 '12 at 23:22
You shouldn't keep the first two entries? If you want to remove rows with & you can use grep('&', A$Address) –  Justin Oct 16 '12 at 23:22
Ah that might be what the OP is after. –  Tyler Rinker Oct 16 '12 at 23:23
What if I want to replace everything starts with '&' to empty record. Should I use gsub? –  Hell_77 Nov 7 '12 at 1:13
add comment

1 Answer

Use grep or grepl to identify which rows contain & then exclude those rows

B <- droplevels(A[!grepl('&', A$Address), ,drop=FALSE])
##       Address
## 3 456 B Street

notice that I wrap the [ call in droplevels to ensure that the unused levels (those with &) are dropped also, as in this case the result would only be 1 line, I included drop=FALSE to keep B as a data.frame

To use grep (which returns the index) you would use -

B <- droplevels(A[-grep('&', A$Address), ,drop=FALSE])
share|improve this answer
grep or grepl will both work, with slightly different syntax. See my edit –  mnel Oct 17 '12 at 0:05
You probably have a variable named F, using drop=FALSE should work –  mnel Oct 17 '12 at 0:09
add comment

Your Answer


