我有以下数据集:
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")
)
我想用值&替换所有行&#39; S&#39;在col1中使用&#39; C&#39;。
这可以按预期工作:
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
答案 0 :(得分: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
非常相似,只是使用字符串而不是裸名字。未提及的水平保持不变。