2020-03-07

Show the first and last n lines of a data frame in R

Problem

We want to show the first and last n lines of a data frame. The equivalent of using the head and tail functions at the same time.

Solution

We can use the function headTail from the psych package.

  1. Defatult options
  2. By default headTail returns the top 4 and bottom 4 lines separated with dots (ellipsis).

    library(psych)
    headTail(ToothGrowth)
    
         len supp dose
    1    4.2   VC  0.5
    2   11.5   VC  0.5
    3    7.3   VC  0.5
    4    5.8   VC  0.5
    ...  ...   ...
    57  26.4   OJ    2
    58  27.3   OJ    2
    59  29.4   OJ    2
    60    23   OJ    2
    
  3. Arguments
  4. We can control tne number of lines to show at the top and the bottom, the ellipsis (how top and bottom are separared), number of columns to show and round the number of digits. Some examples:

    # The first and last 2 lines without separation
    headTail(ToothGrowth, top = 2, bottom = 2, ellipsis = FALSE)
    
        len supp dose
    1   4.2   VC  0.5
    2  11.5   VC  0.5
    59 29.4   OJ  2.0
    60 23.0   OJ  2.0
    
    # The first and last 3, from column 4 to 5 with no decimals.
    headTail(iris, top = 3, bottom = 3, digits = 0 , from = 4, to = 5)
    
       Petal.Width   Species
    1             0    setosa
    2             0    setosa
    3             0    setosa
    ...         ...      
    148           2 virginica
    149           2 virginica
    150           2 virginica
    

Related posts

References

No hay comentarios:

Publicar un comentario

Nube de datos