1 # Licensed to the Apache Software Foundation (ASF) under one
2 # or more contributor license agreements. See the NOTICE file
3 # distributed with this work for additional information
4 # regarding copyright ownership. The ASF licenses this file
5 # to you under the Apache License, Version 2.0 (the
6 # "License"); you may not use this file except in compliance
7 # with the License. You may obtain a copy of the License at
9 # http://www.apache.org/licenses/LICENSE-2.0
11 # Unless required by applicable law or agreed to in writing,
12 # software distributed under the License is distributed on an
13 # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14 # KIND, either express or implied. See the License for the
15 # specific language governing permissions and limitations
18 #' @include arrow-datum.R
20 #' @title Arrow scalars
25 #' @description A `Scalar` holds a single value of an Arrow type.
28 #' `$ToString()`: convert to a string
29 #' `$as_vector()`: convert to an R vector
30 #' `$as_array()`: convert to an Arrow `Array`
31 #' `$Equals(other)`: is this Scalar equal to `other`
32 #' `$ApproxEquals(other)`: is this Scalar approximately equal to `other`
33 #' `$is_valid`: is this Scalar valid
34 #' `$null_count`: number of invalid values - 1 or 0
35 #' `$type`: Scalar type
39 #' @examplesIf arrow_available()
42 #' # If you pass a vector into Scalar$create, you get a list containing your items
43 #' Scalar$create(c(1, 2, 3))
46 #' my_scalar <- Scalar$create(99)
47 #' my_scalar$ApproxEquals(Scalar$create(99.00001)) # FALSE
48 #' my_scalar$ApproxEquals(Scalar$create(99.000009)) # TRUE
49 #' my_scalar$Equals(Scalar$create(99.000009)) # FALSE
50 #' my_scalar$Equals(Scalar$create(99L)) # FALSE (types don't match)
52 #' my_scalar$ToString()
54 Scalar <- R6Class("Scalar",
56 # TODO: document the methods
58 ToString = function() Scalar__ToString(self),
59 type_id = function() Scalar__type(self)$id,
60 as_vector = function() Scalar__as_vector(self),
61 as_array = function(length = 1L) MakeArrayFromScalar(self, as.integer(length)),
62 Equals = function(other, ...) {
63 inherits(other, "Scalar") && Scalar__Equals(self, other)
65 ApproxEquals = function(other, ...) {
66 inherits(other, "Scalar") && Scalar__ApproxEquals(self, other)
70 is_valid = function() Scalar__is_valid(self),
71 null_count = function() sum(!self$is_valid),
72 type = function() Scalar__type(self)
75 Scalar$create <- function(x, type = NULL) {
77 x <- vctrs::unspecified(1)
78 } else if (length(x) != 1 && !is.data.frame(x)) {
82 Array__GetScalar(Array$create(x, type = type), 0)
89 StructScalar <- R6Class("StructScalar",
92 field = function(i) StructScalar__field(self, i),
93 GetFieldByName = function(name) StructScalar__GetFieldByName(self, name)
98 length.Scalar <- function(x) 1L
101 sort.Scalar <- function(x, decreasing = FALSE, ...) x