Skip to content

Commit

Permalink
new dub()
Browse files Browse the repository at this point in the history
@hadley: Do we want this in tibble (#31)?
  • Loading branch information
Kirill Müller committed May 5, 2016
1 parent 2c120a3 commit 54057ce
Show file tree
Hide file tree
Showing 4 changed files with 64 additions and 0 deletions.
1 change: 1 addition & 0 deletions NAMESPACE
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ export(as_data_frame)
export(column_to_rownames)
export(data_frame)
export(data_frame_)
export(dub)
export(frame_data)
export(glimpse)
export(has_rownames)
Expand Down
19 changes: 19 additions & 0 deletions R/dub.R
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
#' Converting atomic vectors to data frames
#'
#' A helper function based on \code{\link{as_data_frame}} and
#' \code{\link{rownames_to_column}}.
#'
#' @param x An atomic vector
#' @param name,value Names of the columns that store the names and values
#'
#' @return
#' @export
#'
#' @examples
#' dub(1:3)
#' dub(c(a = 5, b = 7))
dub <- function(x, name = "name", value = "value") {
x <- rownames_to_column(as_data_frame(x))
names(x) <- c(name, value)
x
}
22 changes: 22 additions & 0 deletions man/dub.Rd

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

22 changes: 22 additions & 0 deletions tests/testthat/test-dub.R
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
context("dub")

test_that("can convert unnamed vector", {
expect_identical(dub(3:1),
data_frame(name = as.character(1:3), value = 3:1))
})

test_that("can convert named vector", {
expect_identical(dub(c(a = 2, b = 1)),
data_frame(name = letters[1:2], value = as.numeric(2:1)))
})

test_that("can convert zero-length vector", {
expect_identical(dub(logical()),
data_frame(name = character(), value = logical()))
})

test_that("can use custom names", {
expect_identical(dub(letters, name = "index", value = "letter"),
data_frame(index = as.character(seq_along(letters)),
letter = letters))
})

1 comment on commit 54057ce

@hadley
Copy link
Member

@hadley hadley commented on 54057ce May 7, 2016

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think the name is to short for something that won't be very common.

And I think an implementation like data_frame(names(x), x) would be a bit clearer

Please sign in to comment.