r - Using grepl to extract a value from text across multiple columns -


i have dataframe (df) containing 2 columns of data state , city. sometimes, however, data inside 2 columns transposed or incorrectly entered. dataframe this:

location          state bangkok                   bangkok metropolitan central thai      bangkok  

i want create new column, "city" extracting 'bangkok' these 2 separate column. can 1 column like:

df$city <- ifelse(grepl("bangkok",df$location),"bangkok","") 

however, want search @ least 2 or more columns @ once, like:

df$city <- ifelse(grepl("bangkok",df$location||df$state),"bangkok","") 

which, obviously, doesn't work. 'filter' in plyr think similar in reverse.

any appreciated. thanks!

you can use grepl more once. besides, should use | rather ||.

df1 <- data.frame(location=c("bangkok", "",  "central thai", "someth"),                    state=c("", "bangkok metropolitan", "bangkok", "youguess"),                   stringsasfactors = false)   df1$city <- ifelse(grepl("bangkok", df1$location) | grepl("bangkok", df1$state),                    "bangkok","") df1 #       location                state    city # 1      bangkok                      bangkok # 2              bangkok metropolitan bangkok # 3 central thai              bangkok bangkok # 4       someth             youguess         

see ?"|"

for |, & , xor logical or raw vector.

for ||, && , istrue, length-one logical vector.


Comments

Popular posts from this blog

sql - VB.NET Operand type clash: date is incompatible with int error -

SVG stroke-linecap doesn't work for circles in Firefox? -

python - TypeError: Scalar value for argument 'color' is not numeric in openCV -