First/last item of an object
last.RdReturns the first/last item of a vector or list, or the first/last row of a data.frame
or data.table. The main difference to head/tail is that the default for n is 1
rather than 6.
Arguments
- x
A vector, list, data.frame or data.table. Otherwise the S3 method of
xts::firstis deployed.- n
A numeric vector length 1. How many items to select.
- ...
Not applicable for
data.tablefirst/last. Any arguments here are passed through toxts's first/last.
Note
For zero-length vectors, first(x) and last(x) mimic head(x, 1) and tail(x, 1) by returning an empty vector instead of NA. However, unlike head()/tail() and base R subsetting (e.g., x[1]), they do not preserve attributes like names.
Value
If no other arguments are supplied it depends on the type of x. The first/last item
of a vector or list. The first/last row of a data.frame or data.table.
For other types, or if any argument is supplied in addition to x (such as n, or
keep in xts) regardless of x's type, then xts::first/
xts::last is called if xts has been loaded, otherwise utils::head/utils::tail.
Examples
first(1:5) # [1] 1
#> [1] 1
x = data.table(x=1:5, y=6:10)
first(x) # same as head(x, 1)
#> x y
#> <int> <int>
#> 1: 1 6
last(1:5) # [1] 5
#> [1] 5
x = data.table(x=1:5, y=6:10)
last(x) # same as tail(x, 1)
#> x y
#> <int> <int>
#> 1: 5 10