head: Retrieve head or tail of a table

Description Usage Arguments Value Implementation Unit tests Author(s) See Also Examples

Description

Retrieves the first or last few records from a dbframe. This function mimics the corresponding data frame methods.

Usage

1
2
3
4
5
## S3 method for class 'dbframe'
head(x, n = 6L, ...)

## S3 method for class 'dbframe'
tail(x, n = 6L, ...)

Arguments

x

A dbframe object

n

An integer. If positive, the number of records to retrieve. If negative, these functions will retrieve all but n records.

...

Other arguments to pass to select

Value

Returns a data frame with the records.

Implementation

head and tail are really basic functions; the implementation is pretty straightforward. The only complication is that the “...” arguments can be passed multiple times, so I pull them out and store them in a list.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
<<*>>=
    head.dbframe <- function(x, n = 6L,...) {
      if (n >= 0) {
        <<Return the first |n| records>>
      } else {
        <<Return all but the last |n| records>>
      }
    }

    tail.dbframe <- function(x, n = 6L,...) {
      if (n >= 0) {
        <<Return the last |n| records>>
      } else {
        <<Return all but the first |n| records>>
      }
    }

We use select statements with “limit” and “offset” to get the records.

1
2
<<Return the first |n| records>>=
    return(select(x, limit = n, as.data.frame = TRUE,...))
1
2
<<Return all but the last |n| records>>=
    return(select(x, limit = n + nrow(x), as.data.frame = TRUE,...))
1
2
3
<<Return the last |n| records>>=
    return(select(x, limit = sprintf("%d,%d", nrow(x) - n, n),
                  as.data.frame = TRUE,...))
1
2
3
<<Return all but the first |n| records>>=
    return(select(x, limit = sprintf("%d,%d", -n, nrow(x) + n),
                  as.data.frame = TRUE,...))

Unit tests

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
<<test-head.R>>=
    library(testthat)
    filename <- tempfile(fileext = ".db")

    data(morley)
    test_that("head and tail return the right number of records", {
      dbf <- dbframe("tab1", dbname = filename, data = morley)
      expect_that(nrow(head(dbf)), equals(6))
      expect_that(nrow(tail(dbf)), equals(6))
  
      nrec <- sample(1:nrow(morley), 1)
      expect_that(nrow(head(dbf, nrec)), equals(nrec))
      expect_that(nrow(tail(dbf, nrec)), equals(nrec))

      expect_that(nrow(head(dbf, -nrec)), equals(nrow(morley) - nrec))
      expect_that(nrow(tail(dbf, -nrec)), equals(nrow(morley) - nrec))
    })

Author(s)

Gray Calhoun gcalhoun@iastate.edu

See Also

head, tail, select

Examples

1
2
3
4
5
6
7
8
data(chickwts)
filename <- tempfile(fileext = ".db")
chicksdb <- dbframe("head1", dbdriver = "SQLite", dbname = filename,
                    data = chickwts)
head(chickwts)
tail(chickwts, -60)
tail(chickwts)
unlink(filename)

grayclhn/dbframe-R-library documentation built on May 17, 2019, 8:33 a.m.