Skip to content
Prev 389022 / 398506 Next

Show only header of str() function

On Thu, 02 Sep 2021, Luigi Marongiu writes:
Perhaps one more solution. You could limit the number
of list components to be printed, though it will leave
a "truncated" message.

    str(iris, list.len = 0)
    ## 'data.frame':    150 obs. of  5 variables:
    ##   [list output truncated]

Since 'str' is a generic function, you could also
define a new 'str' method. Perhaps something among
those lines:

    str.data.frame.oneline <- function (object, ...) {
        cat("'data.frame':\t", nrow(object), " obs. of  ",
            (p <- length(object)), 
            " variable", if (p != 1) "s", "\n", sep = "")
        invisible(NULL)
    }

(which is essentially taken from 'str.data.frame').

Then:

    class(iris) <- c("data.frame.oneline", class(iris))

    str(iris)
    ## 'data.frame':  150 obs. of  5 variables
    
    str(list(a = 1,
             list(b = 2,
                  c = iris)))
    ## List of 2
    ##  $ a: num 1
    ##  $  :List of 2
    ##   ..$ b: num 2
    ##   ..$ c:'data.frame':   150 obs. of  5 variables
Message-ID: <87y28fynrn.fsf@enricoschumann.net>
In-Reply-To: <CAMk+s2Q9QxN9fNdCEyEgjXw4Gvn72K4C=3N2r7cm7Q94g7XX2w@mail.gmail.com> (Luigi Marongiu's message of "Thu, 2 Sep 2021 13:02:05 +0200")