I want to make this statement more generic
mutate(across(
Kingdom:Genus,
~ ifelse(.x == "Incertae sedis", "*Incertae sedis*", .x)
))
how can I indicate "* Incertae sedis *" in a more general way? basically I want to add an asterisk at the beginning and at the end of the string in .x
CodePudding user response:
You could use paste0
:
mutate(across(
Kingdom:Genus,
~ ifelse(.x == "Incertae sedis", paste0("*", .x, "*"), .x)
))
If you have multiple terms that you want to highlight, you could define them in a vector first and use this instead:
uncertain <- c("Incertae sedis", "Problematica", "Nomem Dubium")
df %>% mutate(across(
Kingdom:Genus,
~ ifelse(.x %in% uncertain, paste0("*", .x, "*"), .x)
))
CodePudding user response:
Cave this is experimental:
The answer by @Allan Cameron is best with paste0
But I would like to share this: str_pad
# fake dataframe
df <- tribble(
~A, ~B, ~C,
"Incertae sedis", "blabla", "Incertae sedis",
"Incertae sedis", "blabla", "bloblo",
"Incertae", "Incertae sedis", "blibli"
)
library(dplyr)
library(stringr)
df %>%
mutate(across(A:C, ~ifelse(. == "Incertae sedis", str_pad(., nchar(.) 2, "both", pad="*"), .)))
A B C
<chr> <chr> <chr>
1 *Incertae sedis* blabla *Incertae sedis*
2 *Incertae sedis* blabla bloblo
3 Incertae *Incertae sedis* blibli