-
Notifications
You must be signed in to change notification settings - Fork 37
/
Copy pathexpr__expr.R
3850 lines (3447 loc) · 113 KB
/
expr__expr.R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#' @title Polars Expr
#'
#' @description Polars pl$Expr
#' @rdname Expr
#' @name Expr
#' @keywords Expr
#'
#' @aliases Expr
#'
#' @examples
#' 2+2
#' #Expr has the following methods/constructors
#' ls(rpolars:::Expr)
#'
#' pl$col("this_column")$sum()$over("that_column")
42
#' Print expr
#'
#' @param x Expr
#' @keywords Expr
#'
#' @return self
#' @export
#'
#' @examples
#' pl$col("some_column")$sum()$over("some_other_column")
print.Expr = function(x) {
cat("polars Expr: ")
x$print()
invisible(x)
}
#' internal method print Expr
#' @name Expr$print()
#' @keywords Expr
#' @examples pl$DataFrame(iris)
Expr_print = function() {
.pr$Expr$print(self)
invisible(self)
}
#' @export
#' @title auto complete $-access into object
#' @description called by the interactive R session internally
#' @keywords internal
.DollarNames.Expr = function(x, pattern = "") {
paste0(ls(rpolars:::Expr, pattern = pattern ),"()")
}
#' wrap as literal
#' @param e an Expr(polars) or any R expression
#' @details
#' used internally to ensure an object is an expression
#' @keywords internal
#' @return Expr
#' @examples pl$col("foo") < 5
wrap_e = function(e, str_to_lit = TRUE) {
if(inherits(e,"Expr")) return(e)
if(str_to_lit || is.numeric(e) || is.list(e)) {
pl$lit(e)
} else {
pl$col(e)
}
}
#' Add
#' @description Addition
#' @keywords Expr Expr_operators
#' @param other literal or Robj which can become a literal
#' @return Exprs
#' @examples
#' #three syntaxes same result
#' pl$lit(5) + 10
#' pl$lit(5) + pl$lit(10)
#' pl$lit(5)$add(pl$lit(10))
Expr_add = "use_extendr_wrapper"
#' @export
#' @rdname Expr_add
"+.Expr" <- function(e1,e2) e1$add(wrap_e(e2))
#' Div
#' @description Divide
#' @keywords Expr Expr_operators
#' @param other literal or Robj which can become a literal
#' @return Exprs
#' @examples
#' #three syntaxes same result
#' pl$lit(5) / 10
#' pl$lit(5) / pl$lit(10)
#' pl$lit(5)$div(pl$lit(10))
Expr_div = "use_extendr_wrapper"
#' @export
#' @rdname Expr_div
"/.Expr" <- function(e1,e2) e1$div(wrap_e(e2))
#' Sub
#' @description Substract
#' @keywords Expr Expr_operators
#' @param other literal or Robj which can become a literal
#' @return Exprs
#' @examples
#' #three syntaxes same result
#' pl$lit(5) - 10
#' pl$lit(5) - pl$lit(10)
#' pl$lit(5)$sub(pl$lit(10))
Expr_sub = "use_extendr_wrapper"
#' @export
#' @rdname Expr_sub
"-.Expr" <- function(e1,e2) if(missing(e2)) wrap_e(0L)$sub(e1) else e1$sub(wrap_e(e2))
#' Mul *
#' @description Multiplication
#' @keywords Expr Expr_operators
#' @param other literal or Robj which can become a literal
#' @return Exprs
#' @examples
#' #three syntaxes same result
#' pl$lit(5) * 10
#' pl$lit(5) * pl$lit(10)
#' pl$lit(5)$mul(pl$lit(10))
Expr_mul = "use_extendr_wrapper"
#' @export
#' @rdname Expr_mul
"*.Expr" <- function(e1,e2) e1$mul(wrap_e(e2))
#' Not !
#' @description not method and operator
#' @keywords Expr Expr_operators
#' @param other literal or Robj which can become a literal
#' @return Exprs
#' @examples
#' #two syntaxes same result
#' pl$lit(TRUE)$is_not()
#' !pl$lit(TRUE)
Expr_is_not = "use_extendr_wrapper"
#' @export
#' @rdname Expr_is_not
"!.Expr" <- function(e1,e2) e1$is_not()
#' Less Than <
#' @description lt method and operator
#' @keywords Expr Expr_operators
#' @param other literal or Robj which can become a literal
#' @return Exprs
#' @examples
#' #' #three syntaxes same result
#' pl$lit(5) < 10
#' pl$lit(5) < pl$lit(10)
#' pl$lit(5)$lt(pl$lit(10))
Expr_lt = "use_extendr_wrapper"
#' @export
#' @details
#' See Inf,NaN,NULL,Null/NA translations here \code{\link[rpolars]{docs_translations}}
#' @rdname Expr_lt
"<.Expr" <- function(e1,e2) e1$lt(wrap_e(e2))
#' GreaterThan <
#' @description gt method and operator
#' @keywords Expr Expr_operators
#' @param other literal or Robj which can become a literal
#' @return Exprs
#' @examples
#' #' #three syntaxes same result
#' pl$lit(2) > 1
#' pl$lit(2) > pl$lit(1)
#' pl$lit(2)$gt(pl$lit(1))
Expr_gt = "use_extendr_wrapper"
#' @export
#' @details
#' See Inf,NaN,NULL,Null/NA translations here \code{\link[rpolars]{docs_translations}}
#' @rdname Expr_gt
">.Expr" <- function(e1,e2) e1$gt(wrap_e(e2))
#' Equal ==
#' @description eq method and operator
#' @keywords Expr Expr_operators
#' @param other literal or Robj which can become a literal
#' @return Exprs
#' @examples
#' #' #three syntaxes same result
#' pl$lit(2) == 2
#' pl$lit(2) == pl$lit(2)
#' pl$lit(2)$eq(pl$lit(2))
Expr_eq = "use_extendr_wrapper"
#' @export
#' @details
#' See Inf,NaN,NULL,Null/NA translations here \code{\link[rpolars]{docs_translations}}
#' @rdname Expr_eq
"==.Expr" <- function(e1,e2) e1$eq(wrap_e(e2))
#' Not Equal !=
#' @description neq method and operator
#' @keywords Expr Expr_operators
#' @param other literal or Robj which can become a literal
#' @return Exprs
#' @examples
#' #' #three syntaxes same result
#' pl$lit(1) != 2
#' pl$lit(1) != pl$lit(2)
#' pl$lit(1)$neq(pl$lit(2))
Expr_neq = "use_extendr_wrapper"
#' @export
#' @details
#' See Inf,NaN,NULL,Null/NA translations here \code{\link[rpolars]{docs_translations}}
#' @rdname Expr_neq
"!=.Expr" <- function(e1,e2) e1$neq(wrap_e(e2))
#' Less Than Or Equal <=
#' @description lt_eq method and operator
#' @keywords Expr Expr_operators
#' @param other literal or Robj which can become a literal
#' @return Exprs
#' @examples
#' #' #three syntaxes same result
#' pl$lit(2) <= 2
#' pl$lit(2) <= pl$lit(2)
#' pl$lit(2)$lt_eq(pl$lit(2))
Expr_lt_eq = "use_extendr_wrapper"
#' @export
#' @details
#' See Inf,NaN,NULL,Null/NA translations here \code{\link[rpolars]{docs_translations}}
#' @rdname Expr_lt_eq
"<=.Expr" <- function(e1,e2) e1$lt_eq(wrap_e(e2))
#' Greater Than Or Equal <=
#' @description gt_eq method and operator
#' @keywords Expr Expr_operators
#' @param other literal or Robj which can become a literal
#' @return Exprs
#' @examples
#' #' #three syntaxes same result
#' pl$lit(2) >= 2
#' pl$lit(2) >= pl$lit(2)
#' pl$lit(2)$gt_eq(pl$lit(2))
Expr_gt_eq = "use_extendr_wrapper"
#' @export
#' @details
#' See Inf,NaN,NULL,Null/NA translations here \code{\link[rpolars]{docs_translations}}
#' @rdname Expr_gt_eq
">=.Expr" <- function(e1,e2) e1$gt_eq(wrap_e(e2))
#' aggregate groups
#' @keywords Expr
#' @description
#' Get the group indexes of the group by operation.
#' Should be used in aggregation context only.
#' @return Exprs
#' @export
#' @examples
#' df = pl$DataFrame(list(
#' group = c("one","one","one","two","two","two"),
#' value = c(94, 95, 96, 97, 97, 99)
#' ))
#' df$groupby("group", maintain_order=TRUE)$agg(pl$col("value")$agg_groups())
Expr_agg_groups = "use_extendr_wrapper"
#' Rename Expr output
#' @keywords Expr
#' @description
#' Rename the output of an expression.
#' @param name string new name of output
#' @return Expr
#' @examples pl$col("bob")$alias("alice")
Expr_alias = "use_extendr_wrapper"
#' All (is true)
#' @keywords Expr
#' @description
#' Check if all boolean values in a Boolean column are `TRUE`.
#' This method is an expression - not to be confused with
#' `pl$all` which is a function to select all columns.
#' @aliases all
#' @return Boolean literal
#' @details last `all()` in example is this Expr method, the first `pl$all()` refers
#' to "all-columns" and is an expression constructor
#' @examples
#' pl$DataFrame(list(all=c(T,T),any=c(T,F),none=c(F,F)))$select(pl$all()$all())
Expr_all = "use_extendr_wrapper"
#' Any (is true)
#' @keywords Expr
#' @description
#' Check if any boolean value in a Boolean column is `TRUE`.
#' @return Boolean literal
#' @aliases any
#' @examples
#' pl$DataFrame(list(all=c(T,T),any=c(T,F),none=c(F,F)))$select(pl$all()$any())
Expr_any = "use_extendr_wrapper"
#' Count values (len is a alias)
#' @keywords Expr
#' @name Expr_count
#' @description
#' Count the number of values in this expression.
#' Similar to R length()
#' @return Expr
#' @aliases count
#' @examples
#' pl$DataFrame(list(all=c(T,T),any=c(T,F),none=c(F,F)))$select(pl$all()$count())
Expr_count = "use_extendr_wrapper"
#' Count values (len is a alias)
#' @keywords Expr
#' @rdname Expr_count
#' @return Expr
#' @aliases count len
#' @examples
#' #same as
#' pl$DataFrame(list(all=c(T,T),any=c(T,F),none=c(F,F)))$select(pl$all()$len())
Expr_len = "use_extendr_wrapper"
#' Drop null(s)
#' @keywords Expr
#' @description
#' Drop null values.
#' Similar to R syntax x[!(is.na(x) & !is.nan(x))]
#' @return Expr
#' @details
#' See Inf,NaN,NULL,Null/NA translations here \code{\link[rpolars]{docs_translations}}
#' @examples
#' pl$DataFrame(list(x=c(1,2,NaN,NA)))$select(pl$col("x")$drop_nulls())
Expr_drop_nulls = "use_extendr_wrapper"
#' Drop NaN(s)
#' @keywords Expr
#' @description
#' Drop floating point NaN values.
#' Similar to R syntax x[!is.nan(x)]
#' @details
#'
#' Note that NaN values are not null values! (null corrosponds to R NA, not R NULL)
#' To drop null values, use method `drop_nulls`.
#'
#'
#' See Inf,NaN,NULL,Null/NA translations here \code{\link[rpolars]{docs_translations}}
#'
#' @return Expr
#' @examples
#' pl$DataFrame(list(x=c(1,2,NaN,NA)))$select(pl$col("x")$drop_nans())
Expr_drop_nans = "use_extendr_wrapper"
#' is_null
#' @keywords Expr
#' @description
#' Returns a boolean Series indicating which values are null.
#' Similar to R syntax is.na(x)
#' null polars about the same as R NA
#' @return Expr
#' @details
#' See Inf,NaN,NULL,Null/NA translations here \code{\link[rpolars]{docs_translations}}
#' @examples
#' pl$DataFrame(list(x=c(1,NA,3)))$select(pl$col("x")$is_null())
Expr_is_null = "use_extendr_wrapper"
#' is_not_null
#' @keywords Expr
#' @description
#' Returns a boolean Series indicating which values are not null.
#' Similar to R syntax !is.na(x)
#' null polars about the same as R NA
#' @return Expr
#' @details
#' See Inf,NaN,NULL,Null/NA translations here \code{\link[rpolars]{docs_translations}}
#' @examples
#' pl$DataFrame(list(x=c(1,NA,3)))$select(pl$col("x")$is_not_null())
Expr_is_not_null = "use_extendr_wrapper"
#TODO move this function in to rust with input list of args
#TODO deprecate context feature
#' construct proto Expr array from args
#'
#' @param ... any Expr or string
#'
#'
#' @keywords internal
#'
#' @return ProtoExprArray object
#'
#' @examples rpolars:::construct_ProtoExprArray(pl$col("Species"),"Sepal.Width")
construct_ProtoExprArray = function(...) {
pra = rpolars:::ProtoExprArray$new()
args = list2(...)
arg_names = names(args)
# if args not named load in Expr and string
if(is.null(arg_names)) {
for (i in args) {
# if (is_string(i)) {
# pra$push_back_str(i)
# next
# }
pra$push_back_rexpr(wrap_e(i,str_to_lit = FALSE))
}
#if args named, convert string to col and alias any column by name if a name
} else {
if(!rpolars:::rpolars_optenv$named_exprs) {
stopf("not allowed naming expressions, use `pl$set_rpolars_options(named_exprs = TRUE)` to enable column naming by expression")
}
for (i in seq_along(args)) {
arg = args[[i]]
name = arg_names[i]
expr = wrap_e(arg,str_to_lit = FALSE)
if(nchar(name)>=1L) {
expr = expr$alias(name)
}
pra$push_back_rexpr(expr) #rust method
}
}
pra
}
##TODO allow list to be formed from recursive R lists
##TODO Contribute polars, seems polars now prefer word f or function in map/apply/rolling/apply
# over lambda. However lambda is still in examples.
##TODO Better explain aggregate list
#' Expr_map
#' @keywords Expr
#'
#' @param f a function mapping a series
#' @param output_type NULL or one of pl$dtypes$..., the output datatype, NULL is the same as input.
#' @param agg_list Aggregate list. Map from vector to group in groupby context. Likely not so useful.
#'
#' @rdname Expr_map
#' @return Expr
#' @aliases Expr_map
#' @details user function return should be a series or any Robj convertable into a Series. In PyPolars likely return must be Series.
#' User functions do fully support `browser()`, helpful to investigate.
#' @name Expr_map
#' @examples
#' pl$DataFrame(iris)$select(pl$col("Sepal.Length")$map(\(x) {
#' paste("cheese",as.character(x$to_r_vector()))
#' }, pl$dtypes$Utf8))
Expr_map = function(f, output_type = NULL, agg_list = FALSE) {
.pr$Expr$map(self, f, output_type, agg_list)
}
#' Expr_apply
#' @keywords Expr
#'
#' @description
#'Apply a custom/user-defined function (UDF) in a GroupBy or Projection context.
#'Depending on the context it has the following behavior:
#' -Selection
#' @param f r function see details depending on context
#' @param return_type NULL or one of pl$dtypes, the output datatype, NULL is the same as input.
#'
#' @details
#'
#' Apply a user function in a groupby or projection(select) context
#'
#'
#' Depending on context the following behaviour:
#'
#' * Projection/Selection:
#' Expects an `f` to operate on R scalar values.
#' Polars will convert each element into an R value and pass it to the function
#' The output of the user function will be converted back into a polars type.
#' Return type must match. See param return type.
#' Apply in selection context should be avoided as a `lapply()` has half the overhead.
#'
#' * Groupby
#' Expects a user function `f` to take a `Series` and return a `Series` or Robj convertable to `Series`, eg. R vector.
#' GroupBy context much faster if number groups are quite fewer than number of rows, as the iteration
#' is only across the groups.
#' The r user function could e.g. do vectorized operations and stay quite performant.
#' use `s$to_r()` to convert input Series to an r vector or list. use `s$to_r_vector` and
#' `s$to_r_list()` to force conversion to vector or list.
#'
#'
#' Implementing logic using an R function is almost always _significantly_
#' slower and more memory intensive than implementing the same logic using
#' the native expression API because:
#' - The native expression engine runs in Rust; functions run in R.
#' - Use of R functions forces the DataFrame to be materialized in memory.
#' - Polars-native expressions can be parallelised (R functions cannot*).
#' - Polars-native expressions can be logically optimised (R functions cannot).
#' Wherever possible you should strongly prefer the native expression API
#' to achieve the best performance.
#'
#' @return Expr
#' @aliases Expr_apply
#' @examples
#' #apply over groups - normal usage
#' # s is a series of all values for one column within group, here Species
#' e_all =pl$all() #perform groupby agg on all columns otherwise e.g. pl$col("Sepal.Length")
#' e_sum = e_all$apply(\(s) sum(s$to_r()))$suffix("_sum")
#' e_head = e_all$apply(\(s) head(s$to_r(),2))$suffix("_head")
#' pl$DataFrame(iris)$groupby("Species")$agg(e_sum,e_head)
#'
#'
#' #apply over single values (should be avoided as it takes ~2.5us overhead + R function exec time on a 2015 MacBook Pro)
#' #x is an R scalar
#' e_all =pl$col(pl$dtypes$Float64) #perform on all Float64 columns, using pl$all requires user function can handle any input type
#' e_add10 = e_all$apply(\(x) {x+10})$suffix("_sum")
#' #quite silly index into alphabet(letters) by ceil of float value
#' #must set return_type as not the same as input
#' e_letter = e_all$apply(\(x) letters[ceiling(x)], return_type = pl$dtypes$Utf8)$suffix("_letter")
#' pl$DataFrame(iris)$select(e_add10,e_letter)
#'
#'
#' ##timing "slow" apply in select /with_columns context, this makes apply
#' n = 1000000L
#' set.seed(1)
#' df = pl$DataFrame(list(
#' a = 1:n,
#' b = sample(letters,n,replace=TRUE)
#' ))
#'
#' print("apply over 1 million values takes ~2.5 sec on 2015 MacBook Pro")
#' system.time({
#' rdf = df$with_columns(
#' pl$col("a")$apply(\(x) {
#' x*2L
#' })$alias("bob")
#' )
#' })
#'
#' print("R lapply 1 million values take ~1sec on 2015 MacBook Pro")
#' system.time({
#' lapply(df$get_column("a")$to_r(),\(x) x*2L )
#' })
#' print("using polars syntax takes ~1ms")
#' system.time({
#' (df$get_column("a") * 2L)
#' })
#'
#'
#' print("using R vector syntax takes ~4ms")
#' r_vec = df$get_column("a")$to_r()
#' system.time({
#' r_vec * 2L
#' })
Expr_apply = function(f, return_type = NULL, strict_return_type = TRUE, allow_fail_eval = FALSE) {
#use series apply
wrap_f = function(s) {
s$apply(f, return_type, strict_return_type, allow_fail_eval)
}
#return expression from the functions above, activate agg_list (grouped mapping)
.pr$Expr$map(self, lambda = wrap_f, output_type = return_type, agg_list = TRUE)
}
#' polars literal
#' @keywords Expr
#'
#' @param x an R Scalar, or R vector/list (via Series) into Expr
#' @rdname Expr
#' @return Expr, literal of that value
#' @aliases lit
#' @name Expr_lit
#' @details pl$lit(NULL) translates into a typeless polars Null
#' @examples
#' #scalars to literal, explit `pl$lit(42)` implicit `+ 2`
#' pl$col("some_column") / pl$lit(42) + 2
#'
#' #vector to literal explicitly via Series and back again
#' pl$DataFrame(list())$select(pl$lit(pl$Series(1:4)))$to_list()[[1L]] #R vector to expression and back again
#'
#' #vectors to literal implicitly
#' (pl$lit(2) + 1:4 ) / 4:1
Expr_lit = function(x) {
if(is.null(x)) return(unwrap(.pr$Expr$lit(NULL)))
if (inherits(x,"Expr")) return(x) # already Expr, pass through
if (length(x) != 1L || is.list(x)) x = wrap_s(x) #wrap first as Series if not a scalar
unwrap(.pr$Expr$lit(x)) # create literal Expr
}
#' polars suffix
#' @keywords Expr
#'
#' @param suffix string suffix to be added to a name
#' @rdname Expr
#' @return Expr
#' @aliases suffix
#' @name Expr_suffix
#' @examples pl$col("some")$suffix("_column")
Expr_suffix = function(suffix) {
.pr$Expr$suffix(self, suffix)
}
#' polars prefix
#' @keywords Expr
#'
#' @param prefix string suffix to be added to a name
#' @rdname Expr
#' @return Expr
#' @aliases prefix
#' @name Expr_prefix
#' @examples pl$col("some")$suffix("_column")
Expr_prefix = function(prefix) {
.pr$Expr$prefix(self, prefix)
}
#' polars reverse
#' @keywords Expr
#' @rdname Expr
#' @return Expr
#' @aliases reverse
#' @name Expr_reverse
#' @examples pl$DataFrame(list(a=1:5))$select(pl$col("a")$reverse())
Expr_reverse = function() {
.pr$Expr$reverse(self)
}
#' And
#' @name Expr_and
#' @description combine to boolean exprresions with AND
#' @keywords Expr Expr_operators
#' @param other literal or Robj which can become a literal
#' @return Expr
#' @examples
#' pl$lit(TRUE) & TRUE
#' pl$lit(TRUE)$and(pl$lit(TRUE))
Expr_and = "use_extendr_wrapper"
#' @export
"&.Expr" <- function(e1,e2) e1$and(wrap_e(e2))
#' Or
#' @name Expr_or
#' @description combine to boolean expresions with OR
#' @keywords Expr Expr_operators
#' @param other literal or Robj which can become a literal
#' @return Expr
#' @examples
#' pl$lit(TRUE) | FALSE
#' pl$lit(TRUE)$or(pl$lit(TRUE))
Expr_or = "use_extendr_wrapper"
#' @export
"|.Expr" <- function(e1,e2) e1$or(wrap_e(e2))
#' Xor
#' @name Expr_xor
#' @description combine to boolean expresions with XOR
#' @keywords Expr Expr_operators
#' @param other literal or Robj which can become a literal
#' @return Expr
#' @examples
#' pl$lit(TRUE)$xor(pl$lit(FALSE))
Expr_xor = "use_extendr_wrapper"
#' To physical representation
#' @description expression request underlying physical base representation
#' @keywords Expr
#' @return Expr
#' @aliases to_physical
#' @name Expr_to_physical
#' @examples
#' pl$DataFrame(
#' list(vals = c("a", "x", NA, "a"))
#' )$with_columns(
#' pl$col("vals")$cast(pl$Categorical),
#' pl$col("vals")
#' $cast(pl$Categorical)
#' $to_physical()
#' $alias("vals_physical")
#' )
Expr_to_physical = "use_extendr_wrapper"
#' Cast between DataType(s)
#' @keywords Expr
#' @param dtype DataType to cast to.
#' @param strict bool if true an error will be thrown if cast failed at resolve time.
#' @return Expr
#' @aliases cast
#' @name Expr_cast
#' @aliases cast
#' @examples
#' df = pl$DataFrame(list(a = 1:3, b = 1:3))
#' df$with_columns(
#' pl$col("a")$cast(pl$dtypes$Float64, TRUE),
#' pl$col("a")$cast(pl$dtypes$Int32, TRUE)
#' )
Expr_cast = function(dtype, strict = TRUE) {
.pr$Expr$cast(self, dtype, strict)
}
#' Reverse exponentiation `%**%`(in R `** == ^`)
#' @description Raise a base to the power of the expression as exponent.
#' @keywords Expr
#' @param base real or Expr, the value of the base, self is the exponent
#' @return Expr
#' @name Expr_rpow
#' @details do not use `**`, R secretly parses that just as if it was a `^`
#' @aliases rpow %**%
#' @examples
#' pl$DataFrame(list(a = -1:3))$select(
#' pl$lit(2)$rpow(pl$col("a"))
#')$get_column("a")$to_r() == (-1:3)^2
#'
#' pl$DataFrame(list(a = -1:3))$select(
#' pl$lit(2) %**% (pl$col("a"))
#' )$get_column("a")$to_r() == (-1:3)^2
Expr_rpow = function(base) {
if(!inherits(base,"Expr")) base = pl$lit(base)
expr = .pr$Expr$pow(base,self)
}
#' @export
"%**%" = function(lhs,rhs) rhs^lhs #some default method of what reverse exponentiation is (as python ** operator)
#' @export
"%**%.Expr" <- function(e1,e2) e1$rpow(e2)
#' Square root
#' @description Compute the square root of the elements.
#' @keywords Expr
#' @return Expr
#' @aliases sqrt
#' @name Expr_sqrt
#' @examples
#' pl$DataFrame(list(a = -1:3))$select(pl$col("a")$sqrt())
Expr_sqrt = function() {
self$pow(0.5)
}
#' Compute the exponential, element-wise.
#' @keywords Expr
#' @return Expr
#' @aliases exp
#' @name Expr_exp
#' @format a method
#' @examples
#' log10123 = suppressWarnings(log(-1:3))
#' all.equal(
#' pl$DataFrame(list(a = log10123))$select(pl$col("a")$exp())$as_data_frame()$a,
#' exp(1)^log10123
#' )
Expr_exp = "use_extendr_wrapper"
#' Exclude certain columns from a wildcard/regex selection.
#' @description You may also use regexes in the exclude list. They must start with `^` and end with `$`.
#' @param columns given param type:
#' - string: exclude name of column or exclude regex starting with ^and ending with$
#' - character vector: exclude all these column names, no regex allowed
#' - DataType: Exclude any of this DataType
#' - List(DataType): Excldue any of these DataType(s)
#'
#' @keywords Expr
#' @return Expr
#' @aliases exclude
#' @name Expr_exclude
#' @examples
#'
#' #make DataFrame
#' df = pl$DataFrame(iris)
#'
#' #by name(s)
#' df$select(pl$all()$exclude("Species"))
#'
#' #by type
#' df$select(pl$all()$exclude(pl$Categorical))
#' df$select(pl$all()$exclude(list(pl$Categorical,pl$Float64)))
#'
#' #by regex
#' df$select(pl$all()$exclude("^Sepal.*$"))
#'
#'
Expr_exclude = function(columns) {
#handle lists
if(is.list(columns)) {
columns = pcase(
all(sapply(columns,inherits,"RPolarsDataType")), unwrap(.pr$DataTypeVector$from_rlist(columns)),
all(sapply(columns,is_string)), unlist(columns),
or_else = pstop(err= paste0("only lists of pure RPolarsDataType or String"))
)
}
#dispatch exclude call on types
pcase(
is.character(columns), .pr$Expr$exclude(self, columns),
inherits(columns, "DataTypeVector"), .pr$Expr$exclude_dtype(self,columns),
inherits(columns, "RPolarsDataType"), .pr$Expr$exclude_dtype(self,unwrap(.pr$DataTypeVector$from_rlist(list(columns)))),
or_else = pstop(err= paste0("this type is not supported for Expr_exclude: ", columns))
)
}
#TODO contribute pypolars keep_name example does not showcase an example where the name changes
#' Keep the original root name of the expression.
#'
#' @keywords Expr
#' @return Expr
#' @aliases keep_name
#' @name Expr_keep_name
#' @format a method
#' @examples
#' pl$DataFrame(list(alice=1:3))$select(pl$col("alice")$alias("bob")$keep_name())
Expr_keep_name = "use_extendr_wrapper"
#TODO contribute polars, map_alias unwrap user function errors instead of passing them back
#' Map alias of expression with an R function
#' @description Rename the output of an expression by mapping a function over the root name.
#' @keywords Expr
#' @return Expr
#' @aliases map_alias
#' @name Expr_map_alias
#' @examples
#' pl$DataFrame(list(alice=1:3))$select(pl$col("alice")$alias("joe_is_not_root")$map_alias(\(x) paste0(x,"_and_bob")))
Expr_map_alias = function(fun) {
if (
!rpolars_optenv$no_messages &&
!exists(".warn_map_alias",envir = rpolars:::runtime_state)
) {
assign(".warn_map_alias",1L,envir = rpolars:::runtime_state)
# it does not seem map alias is executed multi-threaded but rather immediately during building lazy query
# if ever crashing, any lazy method like select, filter, with_columns must use something like handle_thread_r_requests()
# then handle_thread_r_requests should be rewritten to handle any type.
message("map_alias function is experimentally without some thread-safeguards, please report any crashes") #TODO resolve
}
if(!is.function(fun)) pstop(err="alias_map fun must be a function")
if(length(formals(fun))==0) pstop(err="alias_map fun must take at least one parameter")
.pr$Expr$map_alias(self,fun)
}
#' Are elements finite
#' @description Returns a boolean output indicating which values are finite.
#'
#' @keywords Expr
#' @return Expr
#' @aliases is_finite
#' @name Expr_is_finite
#' @format a method
#' @details
#' See Inf,NaN,NULL,Null/NA translations here \code{\link[rpolars]{docs_translations}}
#' @examples
#' pl$DataFrame(list(alice=c(0,NaN,NA,Inf,-Inf)))$select(pl$col("alice")$is_finite())
Expr_is_finite = "use_extendr_wrapper"
#' Are elements infinite
#' @description Returns a boolean output indicating which values are infinite.
#' @details
#' See Inf,NaN,NULL,Null/NA translations here \code{\link[rpolars]{docs_translations}}
#' @keywords Expr
#' @return Expr
#' @aliases is_infinite
#' @name Expr_is_infinite
#' @format a method
#' @examples
#' pl$DataFrame(list(alice=c(0,NaN,NA,Inf,-Inf)))$select(pl$col("alice")$is_infinite())
Expr_is_infinite = "use_extendr_wrapper"
#' Are elements NaN's
#' @description Returns a boolean Series indicating which values are NaN.
#' @details Floating point NaN's are a different flag from Null(polars) which is the same as
#' NA_real_(R).
#' See Inf,NaN,NULL,Null/NA translations here \code{\link[rpolars]{docs_translations}}
#' @keywords Expr
#' @return Expr
#' @aliases is_nan
#' @name Expr_is_nan
#'
#' @format a method
#' @examples
#' pl$DataFrame(list(alice=c(0,NaN,NA,Inf,-Inf)))$select(pl$col("alice")$is_nan())
Expr_is_nan = "use_extendr_wrapper"
#' Are elements not NaN's
#' @description Returns a boolean Series indicating which values are not NaN.
#' @details Floating point NaN's are a different flag from Null(polars) which is the same as
#' NA_real_(R).
#' @keywords Expr
#' @return Expr
#' @aliases is_not_nan
#' @details
#' See Inf,NaN,NULL,Null/NA translations here \code{\link[rpolars]{docs_translations}}
#' @name Expr_is_not_nan
#' @format a method
#' @examples
#' pl$DataFrame(list(alice=c(0,NaN,NA,Inf,-Inf)))$select(pl$col("alice")$is_not_nan())
Expr_is_not_nan = "use_extendr_wrapper"
#' Get a slice of this expression.
#'
#' @param offset numeric or expression, zero-indexed where to start slice
#' negative value indicate starting (one-indexed) from back
#' @param length how many elements should slice contain
#'
#' @keywords Expr
#' @return Expr
#' @aliases slice
#' @name Expr_slice
#' @format a method
#' @examples
#'
#' #as head
#' pl$DataFrame(list(a=0:100))$select(
#' pl$all()$slice(0,6)
#' )
#'
#' #as tail
#' pl$DataFrame(list(a=0:100))$select(
#' pl$all()$slice(-6,6)
#' )
Expr_slice = function(offset, length) {
.pr$Expr$slice(self, wrap_e(offset),wrap_e(length))
}
#' Append expressions
#' @description This is done by adding the chunks of `other` to this `output`.
#'
#' @keywords Expr
#' @return Expr
#' @aliases append
#' @name Expr_append
#' @format a method
#' @examples
#' #append bottom to to row
#' df = pl$DataFrame(list(a = 1:3, b = c(NA_real_,4,5)))
#' df$select(pl$all()$head(1)$append(pl$all()$tail(1)))
#'
#' #implicit upcast, when default = TRUE
#' pl$DataFrame(list())$select(pl$lit(42)$append(42L))
#' pl$DataFrame(list())$select(pl$lit(42)$append(FALSE))
#' pl$DataFrame(list())$select(pl$lit("Bob")$append(FALSE))
Expr_append = function(other, upcast=TRUE) {
.pr$Expr$append(self, wrap_e(other), upcast)
}
#' Rechunk memory layout
#' @description Create a single chunk of memory for this Series.
#' @keywords Expr
#' @return Expr
#' @aliases rechunk