Ваш код работает как есть, если вы заключите свои условные выражения в ()
:
Mydata %>%
mutate(
CharColumn1 = case_when(
(Charcolumn2 %in% Charvector) & (Charcolumn3 == "character1") ~ "character2",
(Charcolumn2 %in% Charvector) & (Charcolumn3 == "character2") ~ "character1",
TRUE ~ Charcolumn3))
Вывод:
Charcolumn2 Charcolumn3 CharColumn1
1 d character1 character1
2 e character3 character3
3 d character1 character1
4 a character1 character2
5 a character3 character3
6 c character3 character3
7 b character2 character1
8 c character3 character3
9 b character1 character2
10 a character2 character1
Данные:
library(tidyverse)
set.seed(40)
N <- 10
Charvector <- c("a", "b")
Mydata <- data.frame(Charcolumn2 = sample(letters[1:5], replace=TRUE, size=N),
Charcolumn3 = sample(paste0("character",1:3), replace=TRUE, size=N),
stringsAsFactors = FALSE)