使用 tidyverse,跨越整个数据框,用字符串替换列表中找到的任何字符串。
df<- tribble(
~x, ~y, ~z,
"a", "95%", "96%",
"b", "99%", "98%",
"c", "astricks", "astricks"
)
high95 <- c("95%", "96%", "97%", "98%", "99%", "100%")
试图用字符串 ">95%"替换列表中的任何字符串 (high95)
df %>% str_replace(. %in% high95, ">95%")
我对字符串执行此操作是因为抑制将 col 更改为字符格式。
最佳答案
我们可以使用replace
来创建逻辑表达式
library(dplyr)
df <- df %>%
mutate(across(y:z, ~ replace(., . %in% high95, ">95%")))
-输出
df
# A tibble: 3 × 3
x y z
<chr> <chr> <chr>
1 a >95% >95%
2 b >95% >95%
关于用字符串替换列表中找到的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72619417/