Question

I am new to R development, and have to modify some existing code. Specifically, I need to change a print() call so that it removes extraneous consecutive space characters.

I've found the sanitize.text.function parameter, and have successfully passed it my custom function to the print() function. And it does what I need it to do. That code is as follows:

print(xtable(x,...),type="html",
      sanitize.text.function = function(s) gsub(" {2,}", "", s),...)

Now what I am trying to do is extract the "anonymous" / "inline" function code into a named function like so...

clean <- function(s) { gsub(" {2,}", "", s) }
print(xtable(x,...),type="html",sanitize.text.function = clean(s),...)

However, when I execute this, I get the following:

Error in gsub(" {2,}", "", s) : object 's' not found

The desire to define a function is two-fold:

  1. to create a reusable block of code that could be referenced in other places, and
  2. the ability to add more gsub() or similar executions that may be needed,

For example,

clean <- function(s) { 
    gsub(" {2,}", "", s)
    gsub(">(.*?:)", "<span style=float:left>\1</span>", s)
}

print(xtable(x,...),type="html",sanitize.text.function = clean(s),...)
Was it helpful?

Solution

The sanitize.text.function expects a function yet you pass a result of clean(s) instead of the function (the argument will be evaluated!). So you can either use sanitize.text.function=clean or if you need to re-map arguments sanitize.text.function=function(x) clean(x) which is the lambda (unnamed) function construct you were looking for (the latter makes only sense for something more complex, obviously).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top