Search code examples
rroundingfigure

Rounding only numeric variables with ifelse


I have a very large dataframe (around 100 rows, 200 columns). A subset of my data looks like this:

example <- data.frame("Station" = c("012", "013", "014"), "Value1" = c(145.23453, 1.022342, 0.4432), 
"Value2" = c(2.1221213, 4445.2231412, 0.3333421), "Name" = c("ABC", "SDS", "EFG"))

I would like to round all numeric variables in my table with these conditions.

if x<1, then 1 sig fig

if 1<= x < 99, then 2 sig figs

if x>= 100, then 3 sig figs

I know to do something like this for a specific column:

example$Value1 <- ifelse(example$Value1 < 1, signif(example$Value1, 1), example$Value1)

but I'm not sure what to do for a large dataframe with a mix of numeric and character values.


Solution

  • Just put the ifelse into an lapply. To identify numeric columns use negate is.character in an sapply. You also could Vectorize a small replacement FUNction with all your desired conditions to use in the lapply, which might be convenient. However, note @GKi's comment, that your conditions are not complete.

    nums <- sapply(example, is.numeric)
    
    FUN <- Vectorize(function(x) {
      if (x < 1) x <- signif(x, 1)
      if (1 <= x & x < 99) x <- signif(x, 2)
      if (x >= 100) x <- signif(x, 3)
      x
    })
    
    example[nums] <- lapply(example[nums], FUN)
    #   Station Value1 Value2 Name
    # 1     012  145.0    2.1  ABC
    # 2     013    1.0 4450.0  SDS
    # 3     014    0.4    0.3  EFG