Вы можете написать небольшую новую функцию ifelse.fac
для этой цели.
ifelse.fac <- Vectorize(function(x, y, z) if (x) y else z)
Применение к выходам данных:
dat$newcol <- ifelse.fac(dat$colA == "London", dat$colA, dat$colB)
dat
# colA colB newcol
# 1 London not in France London
# 2 London not in France London
# 3 London not in France London
# 4 London not in France London
# 5 Paris in France in France
# 6 Marseille in France in France
# 7 Paris in France in France
# 8 Paris in France in France
# 9 London not in France London
# 10 Marseille in France in France
И структура факторов остается неизменной:
str(dat)
# 'data.frame': 10 obs. of 3 variables:
# $ colA : Factor w/ 3 levels "London","Marseille",..: 1 1 1 1 3 2 3 3 1 2
# $ colB : Factor w/ 2 levels "in France","not in France": 2 2 2 2 1 1 1 1 2 1
# $ newcol: Factor w/ 5 levels "London","Marseille",..: 1 1 1 1 4 4 4 4 1 4
Данные
dat <- structure(list(colA = structure(c(1L, 1L, 1L, 1L, 3L, 2L, 3L,
3L, 1L, 2L), .Label = c("London", "Marseille", "Paris"), class = "factor"),
colB = structure(c(2L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 2L, 1L
), .Label = c("in France", "not in France"), class = "factor")), row.names = c(NA,
-10L), class = "data.frame")
head(dat)
# colA colB
# 1 London not in France
# 2 London not in France
# 3 London not in France
# 4 London not in France
# 5 Paris in France
# 6 Marseille in France