Skip to content
Permalink
Browse files
add head() and tail(), improved from code by Pat Burns
git-svn-id: https://svn.r-project.org/R/trunk@28111 00db46b3-68df-0310-9c12-caf00c1e9a41
  • Loading branch information
ripley committed Jan 24, 2004
1 parent 61dded7 commit 37271cdbdcd7e5d82c79bdb536ef305d93b644ad
Showing 3 changed files with 92 additions and 0 deletions.
3 NEWS
@@ -211,6 +211,9 @@ NEW FEATURES
o princomp() now warns if both `x' and `covmat' are supplied,
and returns scores only if the centring used is known.

o New functions head() and tail() in package `utils'.
(Based on a contribution by Patrick Burns.)


UTILITIES

@@ -0,0 +1,33 @@
### placed in the public domain 2002
### Patrick Burns patrick@burns-stat.com

head <- function(x, ...) UseMethod("head")

head.default <- function(x, n=6)
{
ans <- x[seq(len=min(n, length(x)))]
if(length(dim(x)) == 1) array(ans, n, list(names(ans))) else ans
}

head.data.frame <- head.matrix <- function(x, n=6)
x[seq(len=min(n, nrow(x))), , drop=FALSE]

head.function <- function(x, n=6) head(deparse(x), n=n)

tail <- function(x, ...) UseMethod("tail")

tail.default <- function(x, n=6)
{
xlen <- length(x)
n <- min(n, xlen)
ans <- x[seq(to=xlen, length=n)]
if(length(dim(x)) == 1) array(ans, n, list(names(ans))) else ans
}

tail.data.frame <- tail.matrix <- function(x, n=6)
{
nrx <- nrow(x)
x[seq(to=nrx, length=min(n, nrx)), , drop=FALSE]
}

tail.function <- function(x, n=6) tail(deparse(x), n=n)
@@ -0,0 +1,56 @@
\name{head}
\alias{head}
\alias{head.default}
\alias{head.data.frame}
\alias{head.function}
\alias{head.matrix}
\alias{tail}
\alias{tail.default}
\alias{tail.data.frame}
\alias{tail.function}
\alias{tail.matrix}

\title{
Return the First or Last Part of an Object
}
\description{
Returns the first or last parts of a vector, matrix, data frame or function.
}
\usage{
head(x, \dots)
\method{head}{default}(x, n=6)
\method{head}{data.frame}(x, n=6)

tail(x, \dots)
\method{tail}{default}(x, n=6)
\method{tail}{data.frame}(x, n=6)
}
\arguments{
\item{x}{an object}
\item{n}{size for the resulting object: number of elements for a
vector (including lists), rows for a matrix or data frame or
lines for a function.}
}
\details{
For matrices and data frames, the first/last \code{n} rows are returned.
For functions, the first/last \code{n} lines of the deparsed function are
returned as character strings.
}
\value{
An object (usually) like \code{x} but generally smaller.
}
\author{
Patrick Burns, improved and corrected by R-core
}

\examples{
data(freeny)
head(freeny.x, n=10)
head(freeny.y)

tail(freeny.x)
tail(freeny.y)

tail(library)
}
\keyword{ manip }

0 comments on commit 37271cd

Please sign in to comment.