Skip to content

Commit

Permalink
feat(Codec): Add row names as a new column
Browse files Browse the repository at this point in the history
  • Loading branch information
nokome committed Dec 22, 2020
1 parent 7020d6d commit 6fbab53
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 6 deletions.
19 changes: 16 additions & 3 deletions R/codec.R
Original file line number Diff line number Diff line change
Expand Up @@ -77,12 +77,25 @@ decode_image_object <- function(value, options = list(), format = "png") {

#' Decode an R `data.frame` to a Stencila `Datatable`
#'
#' If the data frame has row names that are not the default
#' (a sequence from 1 to `nrow`), then the first column will
#' have the name "name" and have the row names as values.
#'
#' @param df The data frame to convert
decode_datatable <- function(df) {
row_names <- attr(df, "row.names")
if (!identical(row_names, seq_len(nrow(df)))) {
columns <- list(decode_datatable_column("name", row_names))
} else {
columns <- NULL
}

columns <- c(columns, filter(lapply(colnames(df), function(colname) {
decode_datatable_column(colname, df[[colname]])
}), function(column) !is.null(column)))

stencilaschema::Datatable(
columns = filter(lapply(colnames(df), function(colname) {
decode_datatable_column(colname, df[[colname]])
}), function(column) !is.null(column))
columns = columns
)
}

Expand Down
6 changes: 3 additions & 3 deletions tests/testthat/test-codec.R
Original file line number Diff line number Diff line change
Expand Up @@ -73,14 +73,14 @@ describe("decode", {
test_that("decodes mtcars", {
datatable <- decode(mtcars)

expect_equal(length(datatable$columns), 11)
expect_equal(length(datatable$columns), 12)
expect_equal(
datatable_colnames(datatable),
c("mpg", "cyl", "disp", "hp", "drat", "wt", "qsec", "vs", "am", "gear", "carb")
c("name", "mpg", "cyl", "disp", "hp", "drat", "wt", "qsec", "vs", "am", "gear", "carb")
)
expect_equal(
datatable_coltypes(datatable),
rep("NumberValidator", 11)
c("StringValidator", rep("NumberValidator", 11))
)
})

Expand Down

0 comments on commit 6fbab53

Please sign in to comment.