[R] Show only header of str() function

Enrico Schumann e@ @end|ng |rom enr|co@chum@nn@net
Thu Sep 2 17:56:28 CEST 2021


On Thu, 02 Sep 2021, Luigi Marongiu writes:

> Hello, is it possible to show only the header (that is: `'data.frame':
> x obs. of  y variables:` part) of the str function?
> Thank you

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




-- 
Enrico Schumann
Lucerne, Switzerland
http://enricoschumann.net



More information about the R-help mailing list