Stataq
Stataq

Reputation: 2297

how to use mutate and gsub together

I am using mutate and paste and gsub to write my code. is it a way I can write it in one chunk?

my codes are:

PMath <- PMath %>% mutate(MathALL = paste(MathMED, MathPR, MathACNOTH, sep = "; "))
PMath$MathALL <- gsub(pattern = "( ; )|(;  $)|\\.",replacement = "", PMath$MathALL, fixed = FALSE)

this code works. Now I rewrite it as:

PMath <- PMath %>%
 mutate(MathALL <- paste(MathMED, MathPR, MathACNOTH, sep = "; ") %>%
    gsub(pattern = "( ; )|(;  $)|\\.",replacement = "", ., fixed = FALSE))

and it won't work. What did I do wrong? Any way to improve this?

Many thanks.

Sample data:

df<-structure(list(tst1 = c("Held", "Held", "Held", "Held", "Held", 
"Held", "Held", "Held"), tst2 = c(NA, NA, NA, "Discont", NA, 
"Discont", NA, NA), tst3 = c(NA, "Med to treat : 10 Ondensetron, 12 Prochloroperazine", 
"Med to treat  : 10 Ondensetron, 12 Prochloroperazine", "Med to treat  : 14 Morphine", 
"Med to treat  : 13 Lovenex, 15 Apixaban, 11 Heparine", NA, NA, 
"Med to treat  : 21 Levaquin"), tst4 = c("1 Stent Placement", 
NA, NA, NA, NA, NA, NA, NA)), row.names = c(NA, -8L), class = c("tbl_df", 
"tbl", "data.frame"))

Upvotes: 1

Views: 119

Answers (1)

akrun
akrun

Reputation: 887183

It is the assignment operator (<-) that is causing the issue. We need = inside tidyverse functions. Also, the data on the rhs of %>% would be .

library(dplyr)
PMath %>%
     mutate(MathALL = paste(MathMED, MathPR, MathACNOTH, sep = "; ") %>%
               gsub(pattern = "( ; )|(;  $)|\\.",
                replacement = "", ., fixed = FALSE))

It is a bit curious that the OP is creating a delimier (; ) and then removing it

In tidyverse, it can be also done with unite

 library(tidyr)
 PMath %>%
        unite(MathAll, MathMED, MathPR, MathACNOTH, sep="; ", na.rm = TRUE)

Upvotes: 1

Related Questions