How to replace elements of vectors based on pipe operator

Viewed 227

Let's say I have below vector

Vec = c("AA", "BB1", "CC2")

Now I want to replace few specific elements based on pattern match as follows

Vec[grepl("[0-9]+$", Vec)] <- paste("CCC", grep("[0-9]+$", Vec, value = T))
Vec
## [1] "AA"      "CCC BB1" "CCC CC2"

How can I execute above step using pipe operator? Below is my try

library(dplyr)

Vec = c("AA", "BB1", "CC2")
Vec %>% `<-`(.[grepl("[0-9]+$", .)], paste("CCC", grep("[0-9]+$", ., value = T)))

With that, I am getting below error

Error in Vec %>% (.[grepl("[0-9]+$", .)] <- paste("CCC", grep("[0-9]+$",  : 
  incorrect number of arguments to "<-"

What is the right approach?

2 Answers

The grepl result is of length 2 while your Vec is of length 3, that's why incorrect number of arguments. So in a {} we can do the grepl stuff, but to give back the entire vector we need another . which is a separate code line achieved with ;.

library(dplyr)
Vec = c("AA", "BB1", "CC2")
Vec %>% {`<-`(.[grepl("[0-9]+$", .)], paste("CCC", grep("[0-9]+$", ., value = T)));.}
# [1] "AA"      "CCC BB1" "CCC CC2"

Alternatively you could use replace.

Vec %>% replace(grepl("[0-9]+$", .), paste("CCC", grep("[0-9]+$", ., value=TRUE)))
# [1] "AA"      "CCC BB1" "CCC CC2"

You could also use str_replace:

Vec %>%
     str_replace('(.*[0-9]+)$', 'CCC \\1')
Related