结合分类因素水平的惯用方法

时间:2015-03-18 21:11:14

标签: r dplyr

以下是我正在尝试做的一个简单的例子:

iris %>%
  mutate(Species2 = ifelse(Species %in% c("setosa", "virginica"), "other", as.character(Species)) %>% as.factor) %>%
  str
# 'data.frame': 150 obs. of  6 variables:
#   $ Sepal.Length: num  5.1 4.9 4.7 4.6 5 5.4 4.6 5 4.4 4.9 ...
# $ Sepal.Width : num  3.5 3 3.2 3.1 3.6 3.9 3.4 3.4 2.9 3.1 ...
# $ Petal.Length: num  1.4 1.4 1.3 1.5 1.4 1.7 1.4 1.5 1.4 1.5 ...
# $ Petal.Width : num  0.2 0.2 0.2 0.2 0.2 0.4 0.3 0.2 0.2 0.1 ...
# $ Species     : Factor w/ 3 levels "setosa","versicolor",..: 1 1 1 1 1 1 1 1 1 1 ...
# $ Species2    : Factor w/ 2 levels "Other","versicolor": 1 1 1 1 1 1 1 1 1 1 ...

但是,如果我想进行多次合并,我最终会使用深度嵌套的ifelse语句,我试图避免这些语句。最优雅的方式是什么?我最好能将解决方案纳入dplyr管道。

2 个答案:

答案 0 :(得分:1)

您可以使用match

species.keep <- c("setosa", "virginica", "other")
iris %>% mutate(Species2 = species.keep[match(Species, species.keep, nomatch=3)])

我们使用nomatch参数match来映射"other" species.keep我们"other"向量的最后一个位置,用于任何以前位置的物种。请注意,这假设as.factor不是有效物种。您必须添加match等,但这应该达到您想要的效果。 {{1}}是R。

中的基线映射函数

答案 1 :(得分:0)

如果需要使用可能的匹配填充初始数组,可能需要使用sapply之类的内容。然后,您可以使用该数组填充Species2:

s <- sapply(levels(iris$Species), 
            function(x) {
                         if (x %in% c("setosa", "virginica")) 
                           x = "Other" 
                         else 
                           x = x
                        }, 
            simplify = F) 

iris %>% 
  mutate(Species2 = (as.character(s[Species])) %>% as.factor) %>%
  str
相关问题