Skip to content
Prev 367293 / 398506 Next

[FORGED] function for remove white space

Try the following function to apply gsub to all character or factor
columns of a data.frame (and maintain change the class of all
columns):

gsubDataFrame <- function(pattern, replacement, x, ...) {
    stopifnot(is.data.frame(x))
    for(i in seq_len(ncol(x))) {
        if (is.character(x[[i]])) {
            x[[i]] <- gsub(pattern, replacement, x[[i]], ...)
        } else if (is.factor(x[[i]])) {
            levels(x[[i]]) <- gsub(pattern, replacement, levels(x[[i]]), ...)
        } # else do nothing for numeric or other column types
    }
    x
}

E.g.,
+                 Int=1:5,
+                 Char=c("a a", "baa", "a a ", " aa", "b a a"),
+                 Fac=factor(c("x x", "yxx", "x x ", " xx", "y x x")))
'data.frame':   5 obs. of  3 variables:
 $ Int : int  1 2 3 4 5
 $ Char: chr  "a a" "baa" "a a " " aa" ...
 $ Fac : Factor w/ 5 levels " xx","x x","x x ",..: 2 5 3 1 4
'data.frame':   5 obs. of  3 variables:
 $ Int : int  1 2 3 4 5
 $ Char: chr  "aa" "baa" "aa" "aa" ...
 $ Fac : Factor w/ 2 levels "xx","yxx": 1 2 1 1 2

Bill Dunlap
TIBCO Software
wdunlap tibco.com
On Tue, Feb 21, 2017 at 11:35 PM, Jos? Luis <josestadistico at gmail.com> wrote: