R Str_remove from multiple columns within pipe

Viewed 3796

I have a dataframe with columns that contain a messy mix of characters and numbers:

col1 col2 col3 col4 col5
x-x  xxx  xx*  xx-  xxx
*y*  yyy  y*y  yy*  yyy

What I want is to remove any characters which match a particular regex pattern.

Now I could just do this a column at a time:

data$col3 <- str_remove(data$col3, "[\\-\\*]")
data$col4 <- str_remove(data$col4, "[\\-\\*]")

But this seems like an unnecessarily clunky solution. What I want is to achieve this with a single command within a pipe, something like:

data<- data %>%
  str_remove(columns 1,3 and 4, "[\\-\\*]")

I would prefer to identify columns by index position, as the column names are lengthy but necessarily so.

1 Answers

We can do it like this:

library(tidyverse)

df1 %>% mutate_at(vars(1,3,4),  funs(gsub("[*-]", "", .)))

 col1 col2 col3 col4 col5
1   xx  xxx   xx   xx  xxx
2    y  yyy   yy   yy  yyy

Note that when using [] in regex, you don't need to escape characters with special meaning, the brackets imply that they are literal already.

Data:

df1 <- structure(list(col1 = structure(2:1, .Label = c("*y*", "x-x"), class = "factor"), 
    col2 = structure(1:2, .Label = c("xxx", "yyy"), class = "factor"), 
    col3 = structure(1:2, .Label = c("xx*", "y*y"), class = "factor"), 
    col4 = structure(1:2, .Label = c("xx-", "yy*"), class = "factor"), 
    col5 = structure(1:2, .Label = c("xxx", "yyy"), class = "factor")), class = "data.frame", row.names = c(NA, 
-2L))
Related