I would like to drop the characters obovate
at second position
df <- data.frame(x = c("Antidesma obovate",
"Ardisia obovate", "Knema obovate", "Lauraceae obovate"))
My desired output
Antidesma
Ardisia
Knema
Lauraceae
I found one topic kind of answering my quesion (Drop characters from string based on position)
but here I need to call specific character that I want to remove.
So far, I only know using str_detect
to change the name right away e.g.
df %>% mutate(x= ifelse(str_detect(x, "Antidesma obovate"), "Antidesma ", x)) %>%
Any suggestions for me, please?
CodePudding user response:
We don't need ifelse
or str_detect
here. Instead, use str_remove
the remove the substring
library(dplyr)
library(stringr)
df %>%
mutate(x = str_remove(x, "\\s obovate"))
x
1 Antidesma
2 Ardisia
3 Knema
4 Lauraceae
CodePudding user response:
Another option is to use gsub
:
gsub(" obovate", "", df$x)
CodePudding user response:
We could use word
from stringr
package:
library(dplyr)
library(stringr)
df %>%
mutate(x = word(x,1))
Output:
x
1 Antidesma
2 Ardisia
3 Knema
4 Lauraceae