Become an expert in R — Interactive courses, Cheat Sheets, certificates and more!
Get Started for Free

first

Return first or last element of an object


Description

Return first or last element of an object. These functions are convenience wrappers for head(x, n=1, ...) and tail(x, n=1, ...).

Usage

first(x, n=1, ...)
last(x, n=1, ...)
first(x, n=1, ...) <- value
last(x, n=1, ...) <- value

Arguments

x

data object

n

a single integer. If positive, 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. If negative, all but the 'n' last/first number of elements of 'x'.

...

arguments to be passed to or from other methods.

value

a vector of values to be assigned (should be of length n)

Value

An object (usually) like 'x' but generally smaller.

Author(s)

Gregory R. Warnes greg@warnes.net

See Also

Examples

## works for vectors..
v <- 1:10
first(v)
last(v)

first(v) <- 9
v

last(v) <- 20
v

## and for lists
l <- list(a=1, b=2, c=3)
first(l)
last(l)

first(l) <- "apple"
last(l)  <- "bannana"
l

## and data.frames
df <- data.frame(a=1:2, b=3:4, c=5:6)
first(df)
last(df)

first(df) <- factor(c("red","green"))
last(df) <- list(c(20,30)) # note the enclosing list!
df

## and matrixes
m <- as.matrix(df)
first(m)
last(m)

first(m) <- "z"
last(m)  <- "q"
m

gdata

Various R Programming Tools for Data Manipulation

v2.18.0
GPL-2
Authors
Gregory R. Warnes, Ben Bolker, Gregor Gorjanc, Gabor Grothendieck, Ales Korosec, Thomas Lumley, Don MacQueen, Arni Magnusson, Jim Rogers, and others
Initial release
2017-06-05

We don't support your browser anymore

Please choose more modern alternatives, such as Google Chrome or Mozilla Firefox.