Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement $name$prefix_fields() and $name$suffix_fields() #873

Merged
merged 5 commits into from
Mar 1, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions NEWS.md
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,8 @@
(#869).
- Converts `clock_time_point` and `clock_zoned_time` objects from
the `{clock}` package to Polars datetime type (#861).
- New methods for the `name` subnamespace: `$prefix_fields()` and
`suffix_fields()` (#873).

## Polars R Package 0.14.1

Expand Down
34 changes: 34 additions & 0 deletions R/expr__name.R
Original file line number Diff line number Diff line change
Expand Up @@ -103,3 +103,37 @@ ExprName_to_uppercase = function() {
.pr$Expr$name_to_uppercase(self) |>
unwrap("in $name$to_uppercase():")
}

#' Add a prefix to all fields name of a struct
#'
#' @param prefix Prefix to add to the field name.
#'
#' @return Expr
#'
#' @examples
#' df = pl$DataFrame(a = 1, b = 2)$select(
#' pl$struct(pl$all())$alias("my_struct")
#' )
#'
#' df$with_columns(pl$col("my_struct")$name$prefix_fields("col_"))$unnest()
ExprName_prefix_fields = function(prefix) {
.pr$Expr$name_prefix_fields(self, prefix) |>
unwrap("in $name$prefix_fields():")
}

#' Add a suffix to all fields name of a struct
#'
#' @param suffix Suffix to add to the field name.
#'
#' @return Expr
#'
#' @examples
#' df = pl$DataFrame(a = 1, b = 2)$select(
#' pl$struct(pl$all())$alias("my_struct")
#' )
#'
#' df$with_columns(pl$col("my_struct")$name$suffix_fields("_post"))$unnest()
ExprName_suffix_fields = function(suffix) {
.pr$Expr$name_suffix_fields(self, suffix) |>
unwrap("in $name$suffix_fields():")
}
4 changes: 4 additions & 0 deletions R/extendr-wrappers.R
Original file line number Diff line number Diff line change
Expand Up @@ -912,6 +912,10 @@ RPolarsExpr$name_suffix <- function(suffix) .Call(wrap__RPolarsExpr__name_suffix

RPolarsExpr$name_prefix <- function(prefix) .Call(wrap__RPolarsExpr__name_prefix, self, prefix)

RPolarsExpr$name_prefix_fields <- function(prefix) .Call(wrap__RPolarsExpr__name_prefix_fields, self, prefix)

RPolarsExpr$name_suffix_fields <- function(suffix) .Call(wrap__RPolarsExpr__name_suffix_fields, self, suffix)

RPolarsExpr$name_to_lowercase <- function() .Call(wrap__RPolarsExpr__name_to_lowercase, self)

RPolarsExpr$name_to_uppercase <- function() .Call(wrap__RPolarsExpr__name_to_uppercase, self)
Expand Down
8 changes: 8 additions & 0 deletions src/rust/src/lazy/dsl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1877,6 +1877,14 @@ impl RPolarsExpr {
Ok(self.0.clone().name().prefix(prefix.as_str()).into())
}

fn name_prefix_fields(&self, prefix: String) -> RResult<Self> {
Ok(self.0.clone().name().prefix_fields(prefix.as_str()).into())
}

fn name_suffix_fields(&self, suffix: String) -> RResult<Self> {
Ok(self.0.clone().name().suffix_fields(suffix.as_str()).into())
}

fn name_to_lowercase(&self) -> RResult<Self> {
Ok(self.0.clone().name().to_lowercase().into())
}
Expand Down
117 changes: 59 additions & 58 deletions tests/testthat/_snaps/after-wrappers.md
Original file line number Diff line number Diff line change
Expand Up @@ -363,64 +363,65 @@
[195] "mode" "mul"
[197] "n_unique" "name_keep"
[199] "name_map" "name_prefix"
[201] "name_suffix" "name_to_lowercase"
[203] "name_to_uppercase" "nan_max"
[205] "nan_min" "neq"
[207] "neq_missing" "new_first"
[209] "new_last" "new_len"
[211] "not" "null_count"
[213] "or" "over"
[215] "pct_change" "peak_max"
[217] "peak_min" "pow"
[219] "print" "product"
[221] "quantile" "rank"
[223] "rechunk" "reinterpret"
[225] "rem" "rep"
[227] "repeat_by" "replace"
[229] "reshape" "reverse"
[231] "rle" "rle_id"
[233] "rolling" "rolling_corr"
[235] "rolling_cov" "rolling_max"
[237] "rolling_mean" "rolling_median"
[239] "rolling_min" "rolling_quantile"
[241] "rolling_skew" "rolling_std"
[243] "rolling_sum" "rolling_var"
[245] "round" "sample_frac"
[247] "sample_n" "search_sorted"
[249] "shift" "shift_and_fill"
[251] "shrink_dtype" "shuffle"
[253] "sign" "sin"
[255] "sinh" "skew"
[257] "slice" "sort"
[259] "sort_by" "std"
[261] "str_base64_decode" "str_base64_encode"
[263] "str_concat" "str_contains"
[265] "str_contains_any" "str_count_matches"
[267] "str_ends_with" "str_explode"
[269] "str_extract" "str_extract_all"
[271] "str_hex_decode" "str_hex_encode"
[273] "str_json_decode" "str_json_path_match"
[275] "str_len_bytes" "str_len_chars"
[277] "str_pad_end" "str_pad_start"
[279] "str_parse_int" "str_replace"
[281] "str_replace_all" "str_replace_many"
[283] "str_reverse" "str_slice"
[285] "str_split" "str_split_exact"
[287] "str_splitn" "str_starts_with"
[289] "str_strip_chars" "str_strip_chars_end"
[291] "str_strip_chars_start" "str_to_date"
[293] "str_to_datetime" "str_to_lowercase"
[295] "str_to_time" "str_to_titlecase"
[297] "str_to_uppercase" "str_zfill"
[299] "struct_field_by_name" "struct_rename_fields"
[301] "sub" "sum"
[303] "tail" "tan"
[305] "tanh" "timestamp"
[307] "to_physical" "top_k"
[309] "unique" "unique_counts"
[311] "unique_stable" "upper_bound"
[313] "value_counts" "var"
[315] "xor"
[201] "name_prefix_fields" "name_suffix"
[203] "name_suffix_fields" "name_to_lowercase"
[205] "name_to_uppercase" "nan_max"
[207] "nan_min" "neq"
[209] "neq_missing" "new_first"
[211] "new_last" "new_len"
[213] "not" "null_count"
[215] "or" "over"
[217] "pct_change" "peak_max"
[219] "peak_min" "pow"
[221] "print" "product"
[223] "quantile" "rank"
[225] "rechunk" "reinterpret"
[227] "rem" "rep"
[229] "repeat_by" "replace"
[231] "reshape" "reverse"
[233] "rle" "rle_id"
[235] "rolling" "rolling_corr"
[237] "rolling_cov" "rolling_max"
[239] "rolling_mean" "rolling_median"
[241] "rolling_min" "rolling_quantile"
[243] "rolling_skew" "rolling_std"
[245] "rolling_sum" "rolling_var"
[247] "round" "sample_frac"
[249] "sample_n" "search_sorted"
[251] "shift" "shift_and_fill"
[253] "shrink_dtype" "shuffle"
[255] "sign" "sin"
[257] "sinh" "skew"
[259] "slice" "sort"
[261] "sort_by" "std"
[263] "str_base64_decode" "str_base64_encode"
[265] "str_concat" "str_contains"
[267] "str_contains_any" "str_count_matches"
[269] "str_ends_with" "str_explode"
[271] "str_extract" "str_extract_all"
[273] "str_hex_decode" "str_hex_encode"
[275] "str_json_decode" "str_json_path_match"
[277] "str_len_bytes" "str_len_chars"
[279] "str_pad_end" "str_pad_start"
[281] "str_parse_int" "str_replace"
[283] "str_replace_all" "str_replace_many"
[285] "str_reverse" "str_slice"
[287] "str_split" "str_split_exact"
[289] "str_splitn" "str_starts_with"
[291] "str_strip_chars" "str_strip_chars_end"
[293] "str_strip_chars_start" "str_to_date"
[295] "str_to_datetime" "str_to_lowercase"
[297] "str_to_time" "str_to_titlecase"
[299] "str_to_uppercase" "str_zfill"
[301] "struct_field_by_name" "struct_rename_fields"
[303] "sub" "sum"
[305] "tail" "tan"
[307] "tanh" "timestamp"
[309] "to_physical" "top_k"
[311] "unique" "unique_counts"
[313] "unique_stable" "upper_bound"
[315] "value_counts" "var"
[317] "xor"

# public and private methods of each class When

Expand Down
39 changes: 0 additions & 39 deletions tests/testthat/test-expr_expr.R
Original file line number Diff line number Diff line change
Expand Up @@ -616,45 +616,6 @@ test_that("exclude", {
)
})

test_that("keep_name", {
expect_identical(
pl$DataFrame(list(alice = 1:3))$select(
pl$col("alice")$alias("bob")$name$keep(),
pl$col("alice")$alias("bob")
)$columns,
c("alice", "bob")
)
})


# TODO find alternative to thread panic test
test_that("$name$map()", {
# skip map_alias thread-guard message
skip_if_not_installed("withr")
withr::with_options(
list(polars.no_messages = TRUE),
{
df = pl$DataFrame(list(alice = 1:3))$select(
pl$col("alice")$alias("joe_is_not_root")$name$map(\(x) paste0(x, "_and_bob"))
)
lf = df$lazy()
expect_identical(lf$collect()$columns, "alice_and_bob")
expect_error(
pl$DataFrame(list(alice = 1:3))$select(
pl$col("alice")$name$map(\(x) 42) # wrong return
),
"was not a string"
)

# expect_error(
# pl$DataFrame(list(alice=1:3))$select(
# pl$col("alice")$name$map(\(x) stop()) #wrong return
# ),
# "^when calling"
# )
}
)
})


test_that("finite infinite is_nan is_not_nan", {
Expand Down
68 changes: 68 additions & 0 deletions tests/testthat/test-expr_name.R
Original file line number Diff line number Diff line change
Expand Up @@ -13,3 +13,71 @@ test_that("name to_uppercase", {
c("VAR1", "VAR2")
)
})

test_that("name keep", {
expect_identical(
pl$DataFrame(list(alice = 1:3))$select(
pl$col("alice")$alias("bob")$name$keep(),
pl$col("alice")$alias("bob")
)$columns,
c("alice", "bob")
)
})

test_that("name map", {
skip_if_not_installed("withr")
withr::with_options(
list(polars.no_messages = TRUE),
{
df = pl$DataFrame(list(alice = 1:3))$select(
pl$col("alice")$alias("joe_is_not_root")$name$map(\(x) paste0(x, "_and_bob"))
)
lf = df$lazy()
expect_identical(lf$collect()$columns, "alice_and_bob")
expect_error(
pl$DataFrame(list(alice = 1:3))$select(
pl$col("alice")$name$map(\(x) 42) # wrong return
),
"was not a string"
)

# TODO: this works but always prints the error message of log("a"), how
# can we silence it?
# expect_error(
# pl$DataFrame(list(alice=1:3))$select(
# pl$col("alice")$name$map(\(x) log("a"))
# )
# )
Comment on lines +44 to +50
Copy link
Collaborator

Choose a reason for hiding this comment

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

How about using suppressWarnings

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

It doesn't work, log("a") generates an error, not a warning. I'd say we can skip this for now, there's another test above for wrong function output

Copy link
Collaborator

Choose a reason for hiding this comment

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

Hmmm, I don't know what this test case is trying to test.
log() is an R function, not a polars one, right?
If it doesn't make sense, why not simply delete the comment?

Copy link
Collaborator Author

@etiennebacher etiennebacher Mar 1, 2024

Choose a reason for hiding this comment

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

We want to test 2 types of errors:

  • the function called in $map() works but doesn't return a string -> Polars error
  • the function called in $map() fails (like log("a")) -> both R and Polars error, and we want to ensure that it doesn't lead to a panick or another issue with threads

The test that is commented out is for the second case. Problem is that it returns the two errors and expect_error() only hides the Polars one, not the R one. Wrapping expect_error() in a second expect_error() doesn't work either.

To clarify, if we uncomment this test, it correctly passes. The only issue is that it prints the error message of log("a") in the output

Copy link
Collaborator

Choose a reason for hiding this comment

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

Thanks for the explanation. Okay, I think we can merge it now for now.

}
)
})

test_that("name prefix_fields", {
df = pl$DataFrame(a = 1, b = 2)$select(
pl$struct(pl$all())$alias("my_struct")
)

expect_identical(
df$with_columns(pl$col("my_struct")$name$prefix_fields("col_"))$unnest()$to_list(),
list(col_a = 1, col_b = 2)
)

expect_error(
pl$DataFrame(a = 1, b = 2)$select(pl$col("a")$name$prefix_fields("col_"))
)
})

test_that("name suffix_fields", {
df = pl$DataFrame(a = 1, b = 2)$select(
pl$struct(pl$all())$alias("my_struct")
)

expect_identical(
df$with_columns(pl$col("my_struct")$name$suffix_fields("_post"))$unnest()$to_list(),
list(a_post = 1, b_post = 2)
)

expect_error(
pl$DataFrame(a = 1, b = 2)$select(pl$col("a")$name$suffix_fields("col_"))
)
})