如何使用dplyr重命名与其他值匹配的值

时间:2017-05-10 00:36:45

标签: r dplyr

我有以下数据框:


df <- structure(list(x1 = 2:5, x2 = c("zz", "333.iv", "333.i.v", "333(100ug)"
)), .Names = c("x1", "x2"), row.names = c(NA, -4L), class = c("tbl_df", 
"tbl", "data.frame"))

df
#>   x1         x2
#> 1  2         zz
#> 2  3     333.iv
#> 3  4    333.i.v
#> 4  5 333(100ug)

对于列x2,我想要做的是将333重命名为所有值 3-33导致:

   x1         x2
   2          zz
   3        3-33
   4        3-33
   5        3-33

我该怎么做?

1 个答案:

答案 0 :(得分:1)

这个怎么样:

df$x2[grepl('333', df$x2, fixed = TRUE)] <- '3-33'
# > df
# x1   x2
# 1  2   zz
# 2  3 3-33
# 3  4 3-33
# 4  5 3-33

使用dplyr

df %>%
    mutate(x2 = ifelse(grepl('333', x2, fixed = TRUE), '3-33', x2))