0

The question I would like to answer is this: "Are the word LIVER or HEART present in x? If so, then print that value in a corresponding row. If not print an NA." I have accomplished this using ifelse() and grepl(). However, I was wondering if there is a better way to search for a value in a string and if the value exists, print it all by itself in a new column. Can anyone recommend a good approach?

x <- c("LIVER 1","HEART COMP 1","CARCASS COMP 1")

y <- ifelse(grepl("LIVER", x), "LIVER", 
       ifelse(grepl("HEART",x), "HEART","NA"))

> data.frame(x,y)

               x     y
1        LIVER 1 LIVER
2   HEART COMP 1 HEART
3 CARCASS COMP 1    NA
boshek
  • 4,100
  • 1
  • 31
  • 55

1 Answers1

1

Using the stringr package which provides a nice regex API:

library(stringr)
x <- c("LIVER 1","HEART COMP 1","CARCASS COMP 1")
y = str_extract(x, "LIVER|HEART")
data.frame(x,y)
# Note that this a true NA value, not a string "NA" as in your question
               x     y
1        LIVER 1 LIVER
2   HEART COMP 1 HEART
3 CARCASS COMP 1  <NA>
Marius
  • 58,213
  • 16
  • 107
  • 105