We're producing Rmd reports which were originally intended for internal use only.
Now these reports are used for external communication as well, with the result that some of the language is incomprehensible for non-insiders. The objective now is to incorporate a mechanism so that the same report can be produced in two versions: one in it's original form and one for external use.
Apart from other stuff the external version also should have internal slang translated to normal language.
My basic idea was to overwrite the print methods with a version which first converts an object to its translated form and then forwards it to the standard print function.
Here what I've tried in a simplified form:
First I created a translate function which exchanges internal slang words for normal words:
dictionary <- data.frame(id = "roomNb", long = "No. of rooms")
translate <- function(x,
language = "long",
translations = dictionary )
{
matched <- match(x, translations$id, 0)
out <- character(length(x))
# translate:
out[matched != 0] <- as.character(translations[[language]][matched] )
# copy other fields:
out[matched == 0] <- as.character(x[matched == 0])
out
}
Now the new print methods for data frame and character vectors:
# overwrite print function for data frame
print.data.frame <- function(x, ...) {
# first translate (only first col here)
out <- x
out[,1] <- translate(x[,1])
# then forward to base print:
base::print.data.frame(out, ...)
}
# overwrite print function for character vector:
print.character <- function(x, ...) {
out <- translate(x)
base::print.default(out, ...)
}
With data frames it works, with character vectors it doesn't:
testDF <- data.frame(a = c("roomNb", "otherStuff"), b = 1:2)
testDF # -> works!
testChar <- c("roomNb" , "otherStuff" )
testChar # Does not work!!
print(testChar) # works, but that's not what I want
According to R Internals section 1.6 if the object has a class attribute it should be auto-printed by the respective method. But this doesn't seem to be the case.
Grateful for any help!