1

Background:

Suppose I have an upper-level function that produces numeric results (e.g., .00235, 2, 8 etc.) and non-numeric results (e.g., "Not Possible", "Result is Unacceptable" etc.).

QUESTION:

I have written a small lower-level function to control the decimal places (called decimal(see below)) shown in R.

How can have my decimal() function to work only when results of my upper-level function are numeric and otherwise let the result to appear as it is (i.e., as a character)?

## decimal display controller:

 decimal <- function(x, k) format(round(x, k), nsmall = k, scientific = 
ifelse(x >= 1e+05 || x <= -1e+05 || x <= 1e-05 & x >= -1e-05, T, F) )   

## Example of use:
 x = .000276573      ## HERE x is a numeric result, what if x = "Not possible"

 decimal(x, 7)
  • Why does your function return different structures? You might consider adopting a simple S3 system for `decimal` (i.e. `decimal = function(x, ...) UseMethod("decimal")` and define a `decimal.character` and `decimal.numeric`) or, even better, for your first function. – alexis_laz Mar 11 '17 at 11:43

1 Answers1

1

You could check typeof for x and return it without processing if it is character.

## decimal display controller:
decimal <- function(x, k){
    if(typeof(x) == "character"){
    return(x)
    }
    format(round(x, k), nsmall = k, scientific = 
        ifelse(x >= 1e+05 || x <= -1e+05 || x <= 1e-05 & x >= -1e-05, T, F) )
}

decimal("sam", 7)
#[1] "sam"
decimal(.3, 7)
#[1] "0.3000000"

Also check out

?is.character
?is.numeric
d.b
  • 32,245
  • 6
  • 36
  • 77
  • 1
    Could you please take a moment to answer [**THIS QUESTION**](http://stackoverflow.com/questions/42937468/changing-the-style-of-a-subscripted-word-not-the-main-word-in-r)? –  Mar 21 '17 at 20:54