pattern, replacement, x, ignore.case, perl, fixed, useBytes: arguments sent to base::gsub()
sortFunc: function used to sort factor levels, which is not performed if the input x is a factor.
...: additional arguments are passed to sortFunc
Returns
factor whose levels are based upon the order of input levels when the input x is a factor; or if the input x is not a factor, it is converted to a factor using the provided sort function sortFunc.
Details
This function is an extension of base::gsub() that returns an ordered factor output. When input is also a factor, the output factor levels are retained in the same order, after applying the string substitution.
This function is very useful when making changes via base::gsub()
to a factor with ordered levels, because it retains the the order of levels after modification.
Tips:
To convert a character vector to a factor, whose levels are sorted, use sortFunc=sort.
To convert a character vector to a factor, whose levels are the order they appear in the input x, use sortFunc=c.
To convert a character vector to a factor, whose levels are sorted alphanumerically, use sortFunc=mixedSort.
Examples
x <- c(paste0( rep(c("first","second","third"),2), rep(c("Section","Choice"), each=3)),"Choice");f <- factor(x, levels=x);f;# default gsub() will return a character vectorgsub("(first|second|third)","", f)# converting to factor resets the factor level orderfactor(gsub("(first|second|third)","", f))## gsubOrdered() maintains the factor level ordergsubOrdered("(first|third)","", f)gsubOrdered("(first)","", f)# to convert character vector to factor, levels in order they appeargsubOrdered("","", x, sortFunc=c)# to convert character vector to factor, levels alphanumeric sortedgsubOrdered("","", x, sortFunc=mixedSort)
See Also
Other jam string functions: asSize(), breaksByVector(), fillBlanks(), formatInt(), gsubs(), makeNames(), nameVector(), nameVectorN(), padInteger(), padString(), pasteByRow(), pasteByRowOrdered(), sizeAsNum(), tcount(), ucfirst()