I was wondering if there is a way to customize round in R such that if one inputs non-numerics (ex. "No"), the round would just output the non-numeric as it is but just round the other numeric input?

Here is what I tried with no success:

a = c(.56789, "No", .87542) ## round numerics but just output the non-numeric

roundif <- function(x, digits) if(any(!is.numeric(x))) x else round(x, digits)

roundif(a, 2)

1 Answers

1
akrun On Best Solutions

We can use grepl to create a logical index for subsetting the numeric elements. In the function, grepl, will check if there any alphabets ([A-Za-z]) in an elements. It could be further generalized to include other characters (if needed)

roundif <- function(x, digits) {
          i1 <- grepl('[A-Za-z]', x) # logical index
           x1 <- as.list(x) # convert to a list
           x1[!i1] <- round(as.numeric(a[!i1]), digits) # assign rounded values 
           x1

   }

roundif(a, 2)
#[[1]]
#[1] 0.57

#[[2]]
#[1] "No"

#[[3]]
#[1] 0.88

NOTE: The vector is converted to a list as vector can hold only a single type