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