【发布时间】:2016-11-22 02:01:56
【问题描述】:
我有以下数据集:
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
【问题讨论】:
-
问题在于
ifelse,它与factors 交互,而不是dplyr- 例如ifelse(x$col1 == 'S', 'C', x$col1)。