Is there a way to display a large number in a table as "Inf"

Hi all,

I need to present a table which is about the size of 10x4. Each cell is unknown, I would like the program to automatically catch really large numbers and display it as "Inf" or something of the sort.

Say if I define "really large" to be > 1,000,000. And with a 3x3 table example:

X, Y, Z
-1, 1, 3
-100,2,5
3,7,99999999

When printed it will display as
X, Y, Z
-1, 1, 3
-100, 2, 5
3, 7, Inf

Thank you all.

You can implement an "override" of sorts - replacing values above a certain threshold by Inf.

This replacement will be permanent though, and will not affect only printing. The actual infinity will be stored and used for all calculations and what not.

If this is the desired behaviour consider the following toy example:

animals <- data.frame(cats = c(-1,-100,3),
                      dogs = c(1,2,7),
                      pigs = c(3,5,500))

animals

  cats dogs pigs
1   -1    1    3
2 -100    2    5
3    3    7  500

# replacing values above 100 by Inf for *all* purposes, 
# including but not limited to print()
animals[animals > 100] <- Inf 

animals

  cats dogs pigs
1   -1    1    3
2 -100    2    5
3    3    7  Inf
1 Like

If you really only want to change the print method, you could define a new class which inherits from data.frame and then change the print method for this class. Then you will see it the way you would like to see it printed, but the object itself will not change. For example (and that might be much more involved than it could be):

DFLim <- setClass("DFLim", contains = "data.frame")

x <- DFLim(data.frame(a = 100*rnorm(10), b = 1000*rnorm(10) ))

print.DFLim <- function(x, threshold) {
    y <- data.frame(x)
    y[y>threshold] = Inf
    print(y)
}

print(x, threshold = 100)
#>              a           b
#> 1     3.671595         Inf
#> 2   -35.882513 -1244.12294
#> 3          Inf         Inf
#> 4   -68.167517    64.37711
#> 5    28.233873 -1548.67899
#> 6          Inf         Inf
#> 7   -64.382301         Inf
#> 8  -175.874444         Inf
#> 9    24.900028         Inf
#> 10   89.431086 -1334.02217

Created on 2019-11-19 by the reprex package (v0.3.0)

2 Likes

Thank you both for the answers!

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.