Skip to content

Commit

Permalink
Error if wrong schema in pl$DataFrame() (#486)
Browse files Browse the repository at this point in the history
  • Loading branch information
etiennebacher authored Nov 9, 2023
1 parent 5aa0603 commit c97f6bd
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 4 deletions.
2 changes: 2 additions & 0 deletions NEWS.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@

- The argument `quote_style` in `$write_csv()` and `$sink_csv()` can now take
the value `"never"` (#483).
- `pl$DataFrame()` now errors if the variables specified in `schema` do not exist
in the data (#486).

# polars 0.10.0

Expand Down
9 changes: 8 additions & 1 deletion R/dataframe__frame.R
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,13 @@ DataFrame
pl$DataFrame = function(..., make_names_unique = TRUE, schema = NULL) {
largs = unpack_list(...)

uw = \(res) unwrap(res, "in $DataFrame():")

if (!is.null(schema) && !all(names(schema) %in% names(largs))) {
Err_plain("Some columns in `schema` are not in the DataFrame.") |>
uw()
}

# no args crete empty DataFrame
if (length(largs) == 0L) {
return(.pr$DataFrame$default())
Expand Down Expand Up @@ -188,7 +195,7 @@ pl$DataFrame = function(..., make_names_unique = TRUE, schema = NULL) {
}) |>
do.call(what = pl$select)
}) |>
unwrap("in pl$DataFrame()")
uw()
}


Expand Down
9 changes: 6 additions & 3 deletions tests/testthat/test-dataframe.R
Original file line number Diff line number Diff line change
Expand Up @@ -160,15 +160,18 @@ test_that("DataFrame, custom schema", {
expect_no_error(
pl$DataFrame(list(schema = 1), schema = list(schema = pl$Float32))
)
# errors if incorrect datatype
# incorrect datatype
expect_error(pl$DataFrame(x = 1, schema = list(schema = foo)))
expect_error(
pl$DataFrame(x = 1, schema = list(x = "foo")),
"expected RPolarsDataType"
)

# TODO: why doesn't this error?
# expect_error(pl$DataFrame(x = 1, schema = list(schema = pl$foo)))
# wrong variable name in schema
expect_error(
pl$DataFrame(x = 1, schema = list(schema = pl$Float32)),
"Some columns in `schema` are not in the DataFrame"
)
})


Expand Down

0 comments on commit c97f6bd

Please sign in to comment.