Hi,
I'm trying to merge all string variables containing "Com" in their names.
I have prepared the code below but mutate_at is not working properly.
library(dplyr)
library(stringr)
TM.data <- data.frame(stringsAsFactors=FALSE,
DF.URN = c("fds", "xdgx", "gvx", "ryh", "jhgjf", "df", "fg", "jgg",
"gjg"),
Rec = c(10, 10, 8, 10, 8, 5, 10, 8, 7),
SatCom = c("Nothing", "Great service.", NA, "NA", "xxxxxx",
"No comment",
NA, NA, NA),
AltTrCom = c("NA", "NA", "NA", "NA", "NA", "…....", "NA", "NA", NA),
EnvCom = c("NA", "NA", "NA", "NA", "NA", "no complaints.", "NA", "NA",
"Car park"),
StaffCom = c("NA", "NA", "bla bla blda", "NA", "NA", "NA", "NA", NA, NA),
ValueCom = c("NA", "NA", "NA", "NA", "Extend the service.", "NA", "NA",
"NA", "NA"),
WaitingCom = c("NA", "NA", "NA", "NA", "NA", "NA", "NA", NA,
"Not applicable"),
WorkComplCom = c("NA", "NA", "NA", "NA", "NA", "NA", "NA", NA,
"Not applicable"),
ContactCom = c("xxx", "no complaints", "NA", "something weird", "NA",
"NA", "NA",
NA,
"Not applicable")
)
TM.data <- TM.data %>%
mutate_at(vars(matches("com$")), ~str_remove_all(.x, "^.{1,5}$"), ~str_remove_all(.x, "^(no\\scomment?|Not\\sApplicable|nothing|^\\s*n.?a.?\\s*$)$"), ~str_remove_all(.x, "^(NA)$")) %>% # Remove blanks
mutate(all_comment = paste(SatCom, AltTrCom, EnvCom, StaffCom, ValueCom, WaitingCom, WorkComplCom, ContactCom, sep="/"), # Merges comment variables
all_comment = str_remove_all(all_comment, "(.)\\1{2,}"), # Removes repeted characters
all_comment = str_remove_all(all_comment, "NA"), # Removes NAs
all_comment = str_remove_all(all_comment, "^(no\\scomment?|Not\\sApplicable|nothing|^\\s*n.?a.?\\s*$)$"), # Removes blanks 2
all_comment = str_remove_all(all_comment, "[:cntrl:]"), # Removes control characters like /n/r
all_comment = str_replace_all(all_comment, "\\s\\s+", " "), #Removes duplicated /
all_comment = str_replace_all(all_comment, "//+", "/")) # Removes extra spaces
TM.data$all_comment <- str_remove(TM.data$all_comment, "/$") # Removes / in the end
TM.data
I still get merged comments with "Not applicable" and "No comment".
Can you help please?