Ответ, предоставленный @ fabian-werner, великолепен, но объекты могут иметь несколько классов, и «factor» не обязательно должен быть первым, возвращаемым class(yes)
, поэтому я предлагаю эту небольшую модификацию, чтобы проверить все атрибуты класса:
safe.ifelse <- function(cond, yes, no) {
class.y <- class(yes)
if ("factor" %in% class.y) { # Note the small condition change here
levels.y = levels(yes)
}
X <- ifelse(cond,yes,no)
if ("factor" %in% class.y) { # Note the small condition change here
X = as.factor(X)
levels(X) = levels.y
} else {
class(X) <- class.y
}
return(X)
}
Я также отправил запрос команде разработчиков R на добавление документированной опции, чтобы base :: ifelse () сохраняла атрибуты на основе выбора пользователем того, какие атрибуты сохранять.Запрос здесь: https://bugs.r -project.org / bugzilla / show_bug.cgi? Id = 16609 - он уже помечен как "WONTFIX" на том основании, что он всегда был таким, каким он являетсясейчас, но я привел дополнительный аргумент о том, почему простое добавление может избавить от головной боли пользователей R.Возможно, ваше «+1» в этой ветке ошибок побудит команду R Core взглянуть еще раз.
РЕДАКТИРОВАТЬ: Вот лучшая версия, которая позволяет пользователю указать, какие атрибуты сохранить, либо «cond» (поведение ifelse () по умолчанию, «yes», поведение в соответствии с приведенным выше кодом или «no» для случаев, когда атрибуты значения «no» лучше:
safe_ifelse <- function(cond, yes, no, preserved_attributes = "yes") {
# Capture the user's choice for which attributes to preserve in return value
preserved <- switch(EXPR = preserved_attributes, "cond" = cond,
"yes" = yes,
"no" = no);
# Preserve the desired values and check if object is a factor
preserved_class <- class(preserved);
preserved_levels <- levels(preserved);
preserved_is_factor <- "factor" %in% preserved_class;
# We have to use base::ifelse() for its vectorized properties
# If we do our own if() {} else {}, then it will only work on first variable in a list
return_obj <- ifelse(cond, yes, no);
# If the object whose attributes we want to retain is a factor
# Typecast the return object as.factor()
# Set its levels()
# Then check to see if it's also one or more classes in addition to "factor"
# If so, set the classes, which will preserve "factor" too
if (preserved_is_factor) {
return_obj <- as.factor(return_obj);
levels(return_obj) <- preserved_levels;
if (length(preserved_class) > 1) {
class(return_obj) <- preserved_class;
}
}
# In all cases we want to preserve the class of the chosen object, so set it here
else {
class(return_obj) <- preserved_class;
}
return(return_obj);
} # End safe_ifelse function