我正在尝试用更复杂的文本替换简单的示例名称。问题描述如下
library(dplyr)
library(ggplot2)
library(clipr)
library(ggpubr)
library(KernSmooth)
library(reshape2)
library(RColorBrewer)
library(stringr)
df <- df %>%
mutate(across('Sample', str_replace, 'A', 'Cat')) %>%
mutate(across('Sample', str_replace, 'B', 'Dog')) %>%
mutate(across('Sample', str_replace, 'C', 'Bat'))
我得到了什么
A = Batat(因为 cat 中的 C 被替换为“Bat”)
如何仅替换仅包含“A”和“A”的文本? 我现在花了几个小时试图解决这个问题,这看起来非常基本。
这里根本不需要‘stringr’,可以使用直接查找或间接循环(基于
match()
):
library(dplyr)
old = c('A', 'B', 'C')
new = c('Cat', 'Dog', 'Bat')
df |> mutate(Sample = new[match(old, Sample)])
或者:
mapping = c(A = 'Cat', B = 'Dog', C = 'Bat')
# Or, if you can’t hard-code the values:
mapping = setNames(new, old)
df |> mutate(Sample = mapping[Sample])