Use Print( ) function to only show certain rows of a column in a data frame

Viewed 471

I'm trying to print only the first 45 rows of a tibble data frame:

print( data_frame_name, n = 45) 

This will return the first 45 rows of my DF.

However, when I tried to specify a column using the dollar sign operator "$" such that

print( data_frame_name$column_name, n = 45) 

R gave me an error message "invalid 'na.print' specification", is there something I am missing?

I would try a workaround method but the problem asks that I use "$" and print().

2 Answers

There are many methods for print (depends on the packages loaded as well) and the print method is dispatched based on the class of the dataset. If we have a tibble object, then the print.tbl is dispatched and it have the n option whereas if the object is not a tibble, a different method is used. When we extract a column, it is a vector. head may be more general

head(data_frame_name$column_name, n = 45)

It can be reproduced with mtcars

print(as_tibble(mtcars), n = 5)
# A tibble: 32 x 11
#    mpg   cyl  disp    hp  drat    wt  qsec    vs    am  gear  carb
#  <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
#1  21       6   160   110  3.9   2.62  16.5     0     1     4     4
#2  21       6   160   110  3.9   2.88  17.0     0     1     4     4
#3  22.8     4   108    93  3.85  2.32  18.6     1     1     4     1
#4  21.4     6   258   110  3.08  3.22  19.4     1     0     3     1
#5  18.7     8   360   175  3.15  3.44  17.0     0     0     3     2
# … with 27 more rows

It works because the print.tbl have the n option

getAnywhere('print.tbl')
function (x, ..., n = NULL, width = NULL, n_extra = NULL) 
{
    cli::cat_line(format(x, ..., n = n, width = width, n_extra = n_extra))
    invisible(x)
}

whereas the arguments for print.data.frame doesn't have

args(print.data.frame)
#function (x, ..., digits = NULL, quote = FALSE, right = TRUE, 
#row.names = TRUE, max = NULL) 

nor does the print.default

args(print.default)
#function (x, digits = NULL, quote = TRUE, na.print = NULL, print.gap = NULL, 
#    right = FALSE, max = NULL, width = NULL, useSource = TRUE, 
#    ...) 

How about

print(data_frame_name$column_name[1:45])

if you're required to use print and $?

Related