首页 文章

如何使用dplyr修改一列因子?

提问于
浏览
0

我有以下数据集:

library(magrittr)
x <- structure(
  list(col1 = structure(
    c(1L, 1L, 2L, 1L, 3L),
    .Label = c("C",
               "Q", "S"),
    class = "factor"
  )),
  .Names = "col1",
  row.names = c(NA, -5L),
  class = c("tbl_df", "data.frame")
)

我想将col1中值为'S'的所有行替换为'C' .

这按预期工作:

x[x$col1 == 'S',] <- 'C'

我尝试使用以下代码使用dplyr进行替换:

x %>%
  dplyr::mutate(col1 = ifelse(col1 == 'S', 'C', col1))

但是它给出了一个整数列,其中每个整数表示因子变量即col1的编码方式的相应级别:

Source: local data frame [5 x 1]

   col1
  (int)
1     1
2     1
3     2
4     1
5     1

为什么dplyr会这样做,使用dplyr进行替换的正确方法是什么?

输出 sessionInfo()

R version 3.3.2 (2016-10-31)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows >= 8 x64 (build 9200)

locale:
[1] LC_COLLATE=English_United States.1252  LC_CTYPE=English_United States.1252   
[3] LC_MONETARY=English_United States.1252 LC_NUMERIC=C                          
[5] LC_TIME=English_United States.1252    

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

other attached packages:
[1] magrittr_1.5

loaded via a namespace (and not attached):
[1] lazyeval_0.2.0 R6_2.1.2       assertthat_0.1 parallel_3.3.2 DBI_0.3.1      tools_3.3.2   
[7] dplyr_0.4.3    Rcpp_0.12.7

1 回答

  • 0

    您可以使用 library(forcats)fct_recode() 调整您的因子,如下所示:

    library(forcats)
    y <- x %>% dplyr::mutate(col1 = fct_recode(col1, "C" = "S"))
    
    levels(x$col1) # original
    [1] "C" "Q" "S"
    levels(y$col1) # new
    [1] "C" "Q"
    

    fct_recode 很像 dplyr::rename 只是用字符串而不是裸名字 . 未提及的水平保持不变 .

相关问题