Dplyr and gsub: how to replace parts of one column with another

Asked

Viewed 823 times

4

I have the following data-frame:

xis <- data.frame(x1=c("**alo.123", "**alo.132", "**alo.199"), x2=c("sp", "mg", "rj"), x3=c(NA))

I would like to create a new column, using gsub as follows:

x3[1] <- gsub("alo", xis$x2[1], xis$x1[1])
x3[2] <- gsub("alo", xis$x2[2], xis$x1[2])
x3[3] <- gsub("alo", xis$x2[3], xis$x1[3])

I would not like to use the for and I know there is the possibility to use the maply for this, as, for example:

xis$x3 <- mapply(gsub,"alo", xis$x2, xis$x1)

There would be a way to use the mutate dplyr for that? Something like:

xis <- mutate(xis, x3 = gsub("alo", x2, x1)

2 answers

3

You can use the str_replace package stringr thus:

require(stringr)
xis <- data.frame(x1=c("**alo.123", "**alo.132", "**alo.199"), x2=c("sp", "mg", "rj"), x3=c(NA))
xis  <- mutate(xis, x3 = str_replace(string = x1, pattern = "alo", replacement = x2))
xis
         x1 x2       x3
1 **alo.123 sp **sp.123
2 **alo.132 mg **mg.132
3 **alo.199 rj **rj.199

2


You can’t use it directly like this because the gsub is not vectored, so only the first element of Replacement will be used, replacing everything with sp.

What the mapplyis doing is vectorize the function, and you could use the function itself mapply within the mutate hassle-free:

xis <- mutate(xis, x3 = mapply(gsub, "alo", x2, x1))
xis
         x1 x2       x3
1 **alo.123 sp **sp.123
2 **alo.132 mg **mg.132
3 **alo.199 rj **rj.199

In Daniel’s answer, the function str_replace of stringr is basically doing this, vectorizing the sub with the mapply. And the str_replace_all is vectorizing the gsub with mapply.

If you want, you can create your own vector function with the mapply or with the Vectorize(a wrapper of mapply) before using inside the mutate. For example:

gsub2<-Vectorize(gsub) # vetoriza o gsub 
xis <- mutate(xis, x3 = gsub2("alo", x2, x1))
xis
         x1 x2       x3
1 **alo.123 sp **sp.123
2 **alo.132 mg **mg.132
3 **alo.199 rj **rj.199

Browser other questions tagged

You are not signed in. Login or sign up in order to post.