[R-pkgs] New package gsubfn
Gabor Grothendieck
ggrothendieck at gmail.com
Tue Mar 28 15:06:59 CEST 2006
gsubfn is a package with one function, gsubfn, that
is like gsub except instead of taking a replacement
string it takes a replacement function. For each
match, that match is passed to the replacement
function along with the backreferences, if any,
and replaced with the output of the function.
If the first two arguments are omitted the defaults
are set to do perl-style (sort of) string interpolation
as in last example.
gsubfn is available for all platforms via CRAN.
# makes all letters except first in word lower case
# output: "I Like A Banana Split"
gsubfn("\\B.", tolower, "I LIKE A BANANA SPLIT")
# adds 1 to each number in third arg
# output: "(11 21)(101 31)"
gsubfn("[[:digit:]]+", function(x) as.numeric(x)+1, "(10 20)(100 30)")
# replaces pairs m:n with their sum
# first argument of f is the match; 2nd & 3rd are the 2 backreferences
# output: "abc 30 def 70 50"
f <- function(x,y,z) as.numeric(y)+as.numeric(z)
gsubfn("([0-9]+):([0-9]+)", f, "abc 10:20 def 30:40 50")
# extracts numbers from string and places them into vector v
# v becomes: 12 34 56 89 12
v <- c(); f <- function(x) v <<- append(v,as.numeric(x))
junk <- gsubfn("[0-9]+", f, "12;34:56,89,,12")
v
# string interpolation (perl-style, somewhat)
# output: pi = 3.14159265358979, 2pi = 6.28318530717959
cat(gsubfn( , , "pi = $pi, 2pi = `2*pi`\n"))
More information about the R-packages
mailing list