pdubois
pdubois

Reputation: 7800

How to rename values that match with another values using dplyr

I have the following dataframe:


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)

For column x2, what I want to do is to rename all values with 333 into 3-33 resulting in:

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

How can I do that?

Upvotes: 0

Views: 451

Answers (1)

mt1022
mt1022

Reputation: 17299

What about this:

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

With dplyr:

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

Upvotes: 1

Related Questions