### No Match Scenario Setup Source: https://vctrs.r-lib.org/reference/internal-faq-matches-algorithm Illustrates a scenario where no match is found because the haystack does not contain the required value. ```R # no match! no y==3 in haystack for x==2 # lower-match will always end up > upper-match in this case loc_lower_match_haystack <- 3L loc_upper_match_haystack <- 2L ``` -------------------------------- ### Vector Prototype and Casting Example Source: https://vctrs.r-lib.org/llms.txt Illustrates finding common prototypes and casting vectors using vctrs functions. ```r # Prototypes vec_ptype_common(FALSE, 1L, 2.5) #> numeric(0) str(vec_cast_common(FALSE, 1L, 2.5)) #> List of 3 #> $ : num 0 #> $ : num 1 #> $ : num 2.5 ``` -------------------------------- ### Install vctrs from CRAN Source: https://vctrs.r-lib.org/llms.txt Standard installation of the vctrs package from CRAN. ```r install.packages("vctrs") ``` -------------------------------- ### Install vctrs Development Version Source: https://vctrs.r-lib.org/llms.txt Installation of the development version of vctrs using the pak package. ```r # install.packages("pak") pak::pak("r-lib/vctrs") ``` -------------------------------- ### Example usage of decimal2 vector Source: https://vctrs.r-lib.org/articles/s3-vector Demonstrates creating a `vctrs_decimal2` vector with different fractional parts and shows its output format. ```R decimal2(10, c(0, 5, 99)) #> #> [1] 10.00 10.05 10.99 ``` -------------------------------- ### Example of POSIXlt record-style object Source: https://vctrs.r-lib.org/articles/s3-vector Demonstrates the underlying structure of POSIXlt, a record-style object, by showing its length and accessing its components. ```r x <- as.POSIXlt(ISOdatetime(2020, 1, 1, 0, 0, 1:3)) x #> [1] "2020-01-01 00:00:01 UTC" "2020-01-01 00:00:02 UTC" #> [3] "2020-01-01 00:00:03 UTC" length(x) #> [1] 3 length(unclass(x)) #> [1] 11 x[[1]] # the first date time #> [1] "2020-01-01 00:00:01 UTC" unclass(x)[[1]] # the first component, the number of seconds #> [1] 1 2 3 ``` -------------------------------- ### Example of maybe_lossy_cast usage Source: https://vctrs.r-lib.org/reference/vctrs-conditions Demonstrates the normal return of maybe_lossy_cast and how it throws an error when lossy casts are present, unless allowed. ```r # Most of the time, `maybe_lossy_cast()` returns its input normally: maybe_lossy_cast( c("foo", "bar"), NA, "", lossy = c(FALSE, FALSE), x_arg = "", to_arg = "" ) #> [1] "foo" "bar" # If `lossy` has any `TRUE`, an error is thrown: try(maybe_lossy_cast( c("foo", "bar"), NA, "", lossy = c(FALSE, TRUE), x_arg = "", to_arg = "" )) #> Error in eval(expr, envir) : #> Can't convert from to due to loss of precision. #> • Locations: 2 # Unless lossy casts are allowed: allow_lossy_cast( maybe_lossy_cast( c("foo", "bar"), NA, "", lossy = c(FALSE, TRUE), x_arg = "", to_arg = "" ) ) #> [1] "foo" "bar" ``` -------------------------------- ### Vector Size and Recycling Example Source: https://vctrs.r-lib.org/llms.txt Demonstrates common vector size calculation and recycling using vctrs functions. ```r library(vctrs) # Sizes vec_size_common(1, 1:10) #> [1] 10 str(vec_recycle_common(1, 1:10)) #> List of 2 #> $ : num [1:10] 1 1 1 1 1 1 1 1 1 1 #> $ : int [1:10] 1 2 3 4 5 6 7 8 9 10 ``` -------------------------------- ### Example Data with Custom LatLon Formatting Source: https://vctrs.r-lib.org/articles/pillar Displays a tibble with a custom `latlon` column, demonstrating the effect of the implemented custom rendering. ```r data #> # A tibble: 6 × 3 #> venue year loc #> #> 1 rstudio::conf 2017 28°20'N 81°33'W #> 2 rstudio::conf 2018 32°43'N 117°10'W #> 3 rstudio::conf 2019 30°16'N 97°44'W #> 4 rstudio::conf 2020 37°47'N 122°25'W #> 5 rstudio::conf 2021 28°30'N 81°24'W #> 6 rstudio::conf 2022 NA ``` -------------------------------- ### Universal Names Example 1 Source: https://vctrs.r-lib.org/reference/vec_as_names Shows how original names are converted to universal names, which are syntactic and safe for direct use in code. Empty and NA names are handled by prepending dots. ```R Original names: "" "x" NA "x" universal names: "...1" "x...2" "...3" "x...4" ``` -------------------------------- ### Using glue string for name specification (outer name only) Source: https://vctrs.r-lib.org/reference/name_spec Demonstrates using a glue string specification to combine outer and inner names. This example uses only the outer name, effectively recycling it. ```r vec_c(name = 1:3, other = 4:5, .name_spec = "{outer}") #> name name name other other #> 1 2 3 4 5 ``` -------------------------------- ### Combine Vectors with vec_c() Source: https://vctrs.r-lib.org/reference/theory-faq-coercion Demonstrates the use of vec_c() for combining vectors. Shows successful combination and an example that results in an error due to incompatible types. ```R vec_c(TRUE, 1) #> [1] 1 1 ``` ```R vec_c("a", 1) #> Error in `vec_c()`: #> ! Can't combine `..1` and `..2` . ``` -------------------------------- ### vec_pany() and vec_pall() Usage Source: https://vctrs.r-lib.org/reference/parallel-operators Demonstrates the basic usage of vec_pany() and vec_pall() with examples showing how they handle missing values and compare to base R functions. ```APIDOC ## vec_pany() and vec_pall() ### Description These functions are parallel variants of `any()` and `all()` that work on multiple inputs at once, similar to `pmin()` and `pmax()`. ### Usage ```r vec_pany( ..., .missing = NA, .size = NULL, .arg = "", .error_call = current_env() ) vec_pall( ..., .missing = NA, .size = NULL, .arg = "", .error_call = current_env() ) ``` ### Arguments - `...`: Logical vectors of equal size. - `.missing`: Value to use when a missing value is encountered. Options are `NA` (propagate missing values), `FALSE` (treat missings as `FALSE`), or `TRUE` (treat missings as `TRUE`). - `.size`: An optional output size. Useful if no inputs might be provided. - `.arg`: Argument name used in error messages. - `.error_call`: The execution environment of a currently running function, used for error reporting. ### Value A logical vector the same size as the input vectors in `...`. ### Details `vec_pany()` and `vec_pall()` are consistent with `any()` and `all()` when there are no inputs. `vec_pany(.size = 1)` returns `FALSE`, and `vec_pall(.size = 1)` returns `TRUE`. ### Examples ```r a <- c(TRUE, TRUE, TRUE, FALSE, FALSE, FALSE, NA, NA, NA) b <- c(TRUE, FALSE, NA, TRUE, FALSE, NA, TRUE, FALSE, NA) # Default behavior treats missings like `|` does vec_pany(a, b) #> [1] TRUE TRUE TRUE TRUE FALSE NA TRUE NA NA a | b #> [1] TRUE TRUE TRUE TRUE FALSE NA TRUE NA NA # Default behavior treats missings like `&` does vec_pall(a, b) #> [1] TRUE FALSE NA FALSE FALSE FALSE NA FALSE NA a & b #> [1] TRUE FALSE NA FALSE FALSE FALSE NA FALSE NA # Remove missings from the computation, like `na_rm = TRUE` vec_pany(a, b, .missing = FALSE) #> [1] TRUE TRUE TRUE TRUE FALSE FALSE TRUE FALSE FALSE (a & !is.na(a)) | (b & !is.na(b)) #> [1] TRUE TRUE TRUE TRUE FALSE FALSE TRUE FALSE FALSE vec_pall(a, b, .missing = TRUE) #> [1] TRUE FALSE TRUE FALSE FALSE FALSE TRUE FALSE TRUE (a | is.na(a)) & (b | is.na(b)) #> [1] TRUE FALSE TRUE FALSE FALSE FALSE TRUE FALSE TRUE # `vec_pall()` can be used to implement a `dplyr::filter()` style API df <- data.frame(id = seq_along(a), a = a, b = b) keep_rows <- function(x, ...) { vec_slice(x, vec_pall(..., .missing = FALSE)) } drop_rows <- function(x, ...) { vec_slice(x, !vec_pall(..., .missing = FALSE)) } # "Keep / Drop the rows when both a and b are TRUE" # These form complements of one another, even with `NA`s. keep_rows(df, a, b) #> id a b #> 1 1 TRUE TRUE drop_rows(df, a, b) #> id a b #> 1 2 TRUE FALSE #> 2 3 TRUE NA #> 3 4 FALSE TRUE #> 4 5 FALSE FALSE #> 5 6 FALSE NA #> 6 7 NA TRUE #> 7 8 NA FALSE #> 8 9 NA NA # Same empty behavior as `any()` and `all()` vec_pany(.size = 1) #> [1] FALSE any() #> [1] FALSE vec_pall(.size = 1) #> [1] TRUE all() #> [1] TRUE ``` ``` -------------------------------- ### Basic vector ordering and sorting Source: https://vctrs.r-lib.org/reference/vec_order Demonstrates the basic usage of `vec_order()` to get sorting indices and `vec_sort()` to sort a numeric vector with NAs. Shows ascending and descending order. ```r x <- round(c(runif(9), NA), 3) vec_order(x) #> [1] 3 6 5 9 1 4 7 2 8 10 vec_sort(x) #> [1] 0.122 0.128 0.207 0.374 0.442 0.561 0.753 0.799 0.895 NA vec_sort(x, direction = "desc") #> [1] NA 0.895 0.799 0.753 0.561 0.442 0.374 0.207 0.128 0.122 ``` -------------------------------- ### Example Usage of Decimal S3 Vector Source: https://vctrs.r-lib.org/articles/s3-vector Demonstrates creating and printing a 'vctrs_decimal' vector with a specified number of decimal places. ```R x <- decimal(runif(10), 1L) x ``` -------------------------------- ### Minimal Names Example Source: https://vctrs.r-lib.org/reference/vec_as_names Illustrates the conversion of original names to minimal names. Unnamed elements become `""`, and `NA` names are also converted to `""`. ```R Original names of a vector with length 3: NULL minimal names: "" "" "" Original names: "x" NA minimal names: "x" "" ``` -------------------------------- ### Unique Names Example Source: https://vctrs.r-lib.org/reference/vec_as_names Demonstrates the transformation of original names into unique names. This process handles empty names, duplicates, and specific patterns like `..#` and `...` by appending suffixes or modifying them. ```R Original names: "" "x" "" "y" "x" "..2" "..." unique names: "...1" "x...2" "...3" "y" "x...5" "...6" "...7" ``` -------------------------------- ### Implementing vec_math Methods for a Custom Class Source: https://vctrs.r-lib.org/articles/s3-vector Example of implementing vec_math methods for a 'vctrs_cached_sum' class. It uses a switch statement to define behavior for 'sum' and 'mean', falling back to base R functions for others. ```r vec_math.vctrs_cached_sum <- function(.fn, .x, ...) { switch(.fn, sum = attr(.x, "sum"), mean = attr(.x, "sum") / length(.x), vec_math_base(.fn, .x, ...) ) } ``` -------------------------------- ### Get ptype and size of a list_of vector Source: https://vctrs.r-lib.org/reference/list-of-attributes Use `list_of_ptype()` to get the prototype of a `list_of` vector and `list_of_size()` to get its size. Returns NULL if no ptype or size is required. ```r x <- list_of(1, 2) list_of_ptype(x) #> numeric(0) list_of_size(x) #> NULL x <- list_of(.ptype = integer(), .size = 5) list_of_ptype(x) #> integer(0) list_of_size(x) #> [1] 5 ``` -------------------------------- ### Step-by-Step Algorithm for `df_locate_matches_recurse()` Source: https://vctrs.r-lib.org/reference/internal-faq-matches-algorithm Illustrates the recursive partitioning and matching process for multi-column data frames, showing how bounds are refined for subsequent columns and iterations. ```r needles <- data_frame(x = c(1, 1, 2, 2, 2, 3), y = c(1, 2, 3, 4, 5, 3)) haystack <- data_frame(x = c(1, 1, 2, 2, 3), y = c(2, 3, 4, 4, 1)) needles #> x y #> 1 1 1 #> 2 1 2 #> 3 2 3 #> 4 2 4 #> 5 2 5 #> 6 3 3 haystack #> x y #> 1 1 2 #> 2 1 3 #> 3 2 4 #> 4 2 4 #> 5 3 1 ## Column 1, iteration 1 # start at midpoint in needles # this corresponds to x==2 loc_mid_needles <- 3L # finding all x==2 values in needles gives us: loc_lower_duplicate_needles <- 3L loc_upper_duplicate_needles <- 5L # finding matches in haystack give us: loc_lower_match_haystack <- 3L loc_upper_match_haystack <- 4L # compute LHS/RHS bounds for next needle lhs_loc_lower_bound_needles <- 1L # original lower bound lhs_loc_upper_bound_needles <- 2L # lower_duplicate-1 rhs_loc_lower_bound_needles <- 6L # upper_duplicate+1 rhs_loc_upper_bound_needles <- 6L # original upper bound # We still have a 2nd column to check. So recurse and pass on the current # duplicate and match bounds to start the 2nd column with. ## Column 2, iteration 1 # midpoint of [3, 5] # value y==4 loc_mid_needles <- 4L loc_lower_duplicate_needles <- 4L loc_upper_duplicate_needles <- 4L loc_lower_match_haystack <- 3L loc_upper_match_haystack <- 4L # last column, so record matches # - this was location 4 in needles # - lower match in haystack is at loc 3 # - match size is 2 # Now handle LHS and RHS of needle midpoint lhs_loc_lower_bound_needles <- 3L # original lower bound lhs_loc_upper_bound_needles <- 3L # lower_duplicate-1 rhs_loc_lower_bound_needles <- 5L # upper_duplicate+1 rhs_loc_upper_bound_needles <- 5L # original upper bound ## Column 2, iteration 2 (using LHS bounds) # midpoint of [3,3] # value of y==3 loc_mid_needles <- 3L ``` -------------------------------- ### Combine Data Frames with vec_rbind() Source: https://vctrs.r-lib.org/reference/theory-faq-coercion Illustrates combining data frames using vec_rbind(). Shows a successful combination where types are compatible and an example that fails due to incompatible column types. ```R vec_rbind( data.frame(x = TRUE), data.frame(x = 1, y = 2) ) #> x y #> 1 1 NA #> 2 1 2 ``` ```R vec_rbind( data.frame(x = "a"), data.frame(x = 1, y = 2) ) #> Error in `vec_rbind()`: #> ! Can't combine `..1$x` and `..2$x` . ``` -------------------------------- ### Example usage of `if_else` with different types Source: https://vctrs.r-lib.org/articles/stability Demonstrates the `if_else` function with various data types including numeric, factor, and Date. It shows how `if_else` correctly determines the output type based on the common type of `yes` and `no` arguments. ```R x <- c(NA, 1:4) if_else(x > 2, "small", "big") #> [1] NA "big" "big" "small" "small" ``` ```R if_else(x > 2, factor("small"), factor("big")) #> [1] big big small small #> Levels: small big ``` ```R if_else(x > 2, Sys.Date(), Sys.Date() + 7) #> [1] NA "2026-04-24" "2026-04-24" "2026-04-17" "2026-04-17" ``` -------------------------------- ### Version String Combination with List Wrapping using c() Source: https://vctrs.r-lib.org/articles/stability Demonstrates that c() wraps a string and a version string into a list when the version string is provided second. ```r c("x", getRversion()) #> [[1]] #> [1] "x" #> #> [[2]] #> [1] 4 5 3 ``` -------------------------------- ### Get prototype of a single vector Source: https://vctrs.r-lib.org/reference/vec_ptype Use `vec_ptype()` to get the unspecified prototype of a single vector. The `...` argument must be empty. ```r vec_ptype(1:3) ``` -------------------------------- ### Get sizes of list elements Source: https://vctrs.r-lib.org/reference/vec_size Use `list_sizes()` to get an integer vector of the sizes of each element in a list. This function errors on non-list inputs. ```r list_sizes(list("a", 1:5, letters)) #> [1] 1 5 26 ``` -------------------------------- ### Error example with 'inner' specification Source: https://vctrs.r-lib.org/reference/name_spec This example shows that even when using the 'inner' name specification, type mismatches between vectors will still result in an error. ```r try(vec_c(x = c(a = 1), y = c(b = "2"), .name_spec = "inner")) #> Error in vec_c(x = c(a = 1), y = c(b = "2"), .name_spec = "inner") : #> Can't combine `x` and `y` . ``` -------------------------------- ### Create Zero-Length Vectors with Constructors Source: https://vctrs.r-lib.org/articles/s3-vector Demonstrates calling the low-level and user-friendly constructors without arguments to create zero-length vectors, useful for prototypes. ```r new_percent() #> percent() #> ``` -------------------------------- ### Get or set observations in a vector Source: https://vctrs.r-lib.org/reference/vec_slice Use `vec_slice()` to get or set observations in a vector. The assignment form `vec_slice(x, i) <- value` is used for setting values. ```APIDOC ## vec_slice() ### Description Provides a common interface to extracting and modifying observations for all vector types, regardless of dimensionality. They are analogs to `[` and `[<-` that match `vec_size()` instead of `length()`. ### Usage ```r vec_slice(x, i, ..., error_call = current_env()) vec_slice(x, i) <- value ``` ### Arguments - x: A vector - i: An integer, character or logical vector specifying the locations or names of the observations to get/set. Specify `TRUE` to index all elements (as in `x[]`), or `NULL`, `FALSE` or `integer()` to index none (as in `x[NULL]`) - ...: These dots are for future extensions and must be empty. - error_call: The execution environment of a currently running function, e.g. `caller_env()`. The function will be mentioned in error messages as the source of the error. See the `call` argument of `abort()` for more information. - value: A vector of replacement values. `value` is cast to the type of `x`. If `slice_value = FALSE`, `value` must be size 1 or the same size as `i` after `i` has been converted to a positive integer location vector with `vec_as_location()` (which may not be the same size as `i` originally). If `slice_value = TRUE`, `value` must be size 1 or the same size as `x`. - slice_value: A boolean. If `TRUE`, the assignment proceeds as if you had provided `vec_slice(x, i) <- vec_slice(value, i)`, but is optimized to avoid materializing the slice of `value`. - x_arg, value_arg: Argument names for `x` and `value`. These are used in error messages to inform the user about the locations of incompatible types and sizes (see `stop_incompatible_type()` and `stop_incompatible_size()`). ``` -------------------------------- ### Create a list of integers Source: https://vctrs.r-lib.org/reference/list_of Demonstrates creating a list where each element must be an integer. The type is explicitly set using `integer()`. ```r library(vctrs) # Create a list of integers list_of(1L, 2L, 3L, .ptype = integer()) ``` -------------------------------- ### Get common prototype without finalization Source: https://vctrs.r-lib.org/reference/vec_ptype Set `.finalise = FALSE` in `vec_ptype_common()` to get an unfinalised common type. This is useful for advanced type manipulation with `vec_ptype2()`. ```r vec_ptype_common(1:3, 1.0:3.0, .finalise = FALSE) ``` -------------------------------- ### Create a list of fixed size Source: https://vctrs.r-lib.org/reference/list_of Demonstrates creating a list where each element must have a specific size (e.g., 2). `.size` is set to a scalar integer. ```r library(vctrs) # Create a list where each element has size 2 list_of(c(1, 2), c(3, 4), .size = 2) ``` -------------------------------- ### Get vector size Source: https://vctrs.r-lib.org/reference/vec_size Use `vec_size()` to get the number of observations for a vector, matrix, or data frame. It is equivalent to `NROW()` but throws an error on non-vector inputs. ```r vec_size(1:100) #> [1] 100 vec_size(mtcars) #> [1] 32 vec_size(array(dim = c(3, 5, 10))) #> [1] 3 ``` -------------------------------- ### vec_proxy for vctrs_list_of Source: https://vctrs.r-lib.org/reference/vec_proxy Example of implementing vec_proxy for a 'vctrs_list_of' class to unclass it. ```r vec_proxy.vctrs_list_of <- function(x) { unclass(x) } ``` -------------------------------- ### Create a list with both type and size restrictions Source: https://vctrs.r-lib.org/reference/list_of Demonstrates creating a list with both type (integer) and size (3) constraints on its elements. ```r library(vctrs) # Create a list of integers, each of size 3 list_of(1:3, 4:6, .ptype = integer(), .size = 3) ``` -------------------------------- ### vec_proxy for POSIXlt Source: https://vctrs.r-lib.org/reference/vec_proxy Example of implementing vec_proxy for POSIXlt to return a data frame. ```r vec_proxy.POSIXlt <- function(x) { new_data_frame(unclass(x)) } ``` -------------------------------- ### Basic Usage of vec_proxy and vec_restore Source: https://vctrs.r-lib.org/reference/vec_proxy Shows the basic function signatures for vec_proxy and vec_restore. ```r vec_proxy(x, ...) vec_restore(x, to, ...) ``` -------------------------------- ### Basic Usage of vec_expand_grid() Source: https://vctrs.r-lib.org/reference/vec_expand_grid Demonstrates the fundamental usage of vec_expand_grid() to create a grid from two input vectors. ```r vec_expand_grid(x = 1:2, y = 1:3) #> x y #> 1 1 1 #> 2 1 2 #> 3 1 3 #> 4 2 1 #> 5 2 2 #> 6 2 3 ``` -------------------------------- ### Get unique rational vectors Source: https://vctrs.r-lib.org/articles/s3-vector Demonstrates the use of `unique()` with a rational vector, which relies on the `vec_proxy_equal` method. ```r unique(x) #> #> [1] 1/1 2/1 1/2 ``` -------------------------------- ### Get Common Size with Recycling Source: https://vctrs.r-lib.org/reference/theory-faq-recycling Uses `vec_size_common()` to determine the common size of vectors after applying recycling rules. ```R vec_size_common(1:3, "x") #> [1] 3 ``` -------------------------------- ### vec_slice Source: https://vctrs.r-lib.org/reference/vec_slice Extracts a subset of a vector. It can be used to get elements at specific positions or to assign new values to a subset of a vector. ```APIDOC ## vec_slice ### Description Extracts a subset of a vector. It can be used to get elements at specific positions or to assign new values to a subset of a vector. ### Usage ```r vec_slice(x, i) vec_slice(x, i) <- value ``` ### Arguments * `x`: The vector to slice. * `i`: The indices to slice. Can be a vector of integers, logicals, or character strings. * `value`: The value to assign to the sliced elements (for the assignment variant). ### Details The assignment variant `vec_slice(x, i) <- value` modifies the vector `x` in place or returns a new vector with the assigned values, depending on the context. The function aims for type stability, ensuring that the output type is consistent with the input type where possible. It handles slicing for multi-dimensional objects as well. ### Examples ```r x <- sample(10) vec_slice(x, 1:3) # Assigning with the infix variant: vec_slice(x, 2) <- 100 # Assigning with the regular variant that doesn't modify the original input: y <- vec_assign(x, 3, 500) # Slicing objects of higher dimension: vec_slice(mtcars, 1:3) ``` ``` -------------------------------- ### Create a list with no size restriction Source: https://vctrs.r-lib.org/reference/list_of Illustrates creating a list where element sizes are not restricted. `rlang::zap()` is used for `.size`. ```r library(vctrs) # Create a list with no size restriction list_of(1, c(1, 2), .size = rlang::zap()) ``` -------------------------------- ### Incompatible arithmetic operations for 'vctrs_meter' Source: https://vctrs.r-lib.org/articles/s3-vector Shows examples of arithmetic operations that are not permitted for the 'vctrs_meter' class, resulting in errors from vec_arith(). ```R x + 1 meter(10) + meter(1) meter(10) * 3 ``` -------------------------------- ### Create and Display Custom Tibble Source: https://vctrs.r-lib.org/reference/howto-faq-coercion-data-frame Demonstrates creating an instance of `my_tibble` with a 'red' colour and sample data, and then displaying it to show the custom print method output. ```R red <- my_tibble("red", x = 1, y = 1:2) red ``` -------------------------------- ### Basic Ranking with Ties Source: https://vctrs.r-lib.org/reference/vec_rank Demonstrates basic ranking of an integer vector using different tie-breaking methods ('min', 'max'). ```r x <- c(5L, 6L, 3L, 3L, 5L, 3L) vec_rank(x, ties = "min") #> [1] 4 6 1 1 4 1 vec_rank(x, ties = "max") #> [1] 5 6 3 3 5 3 ``` -------------------------------- ### Creating list columns with data_frame() Source: https://vctrs.r-lib.org/reference/data_frame Shows how to create list columns easily by passing lists as inputs to data_frame(). It's recommended to convert to a tibble for better printing. ```r df <- data_frame(x = list(1:2, 2, 3:4), y = 3:1) # However, the base print method is suboptimal for displaying them, # so it is recommended to convert them to tibble if (rlang::is_installed("tibble")) { tibble::as_tibble(df) } #> # A tibble: 3 × 2 #> x y #> #> 1 3 #> 2 2 #> 3 1 ``` -------------------------------- ### Instantiate the natural number class Source: https://vctrs.r-lib.org/reference/howto-faq-coercion Demonstrates creating instances of the 'my_natural' class with integer and NA values. ```R new_natural(1:3) #> #> [1] 1 2 3 new_natural(c(1, NA)) #> #> [1] 1 NA ``` -------------------------------- ### Test self-self vec_ptype2 coercion Source: https://vctrs.r-lib.org/reference/howto-faq-coercion Example of calling vec_ptype2() with two instances of a custom class to observe the coercion result. ```R vec_ptype2(new_natural(1), new_natural(2:3)) ``` -------------------------------- ### Using glue string for name specification (outer and inner) Source: https://vctrs.r-lib.org/reference/name_spec Shows how to use a glue string with both '{outer}' and '{inner}' to create combined names for the resulting vector. ```r vec_c(name = 1:3, other = 4:5, .name_spec = "{outer}_{inner}") #> name_1 name_2 name_3 other_1 other_2 #> 1 2 3 4 5 ``` -------------------------------- ### Get Rowwise Names with vec_names() Source: https://vctrs.r-lib.org/reference/vec_names Consistently retrieves the rowwise names for data frames and arrays. Returns NULL if the object is unnamed. ```r vec_names(data.frame(a = 1, b = 2)) #> NULL names(data.frame(a = 1, b = 2)) #> [1] "a" "b" vec_names(mtcars) #> [1] "Mazda RX4" "Mazda RX4 Wag" "Datsun 710" #> [4] "Hornet 4 Drive" "Hornet Sportabout" "Valiant" #> [7] "Duster 360" "Merc 240D" "Merc 230" #> [10] "Merc 280" "Merc 280C" "Merc 450SE" #> [13] "Merc 450SL" "Merc 450SLC" "Cadillac Fleetwood" #> [16] "Lincoln Continental" "Chrysler Imperial" "Fiat 128" #> [19] "Honda Civic" "Toyota Corolla" "Toyota Corona" #> [22] "Dodge Challenger" "AMC Javelin" "Camaro Z28" #> [25] "Pontiac Firebird" "Fiat X1-9" "Porsche 914-2" #> [28] "Lotus Europa" "Ford Pantera L" "Ferrari Dino" #> [31] "Maserati Bora" "Volvo 142E" names(mtcars) #> [1] "mpg" "cyl" "disp" "hp" "drat" "wt" "qsec" "vs" "am" #> [10] "gear" "carb" vec_names(Titanic) #> [1] "1st" "2nd" "3rd" "Crew" names(Titanic) #> NULL ``` -------------------------------- ### vec_order() and vec_sort() Source: https://vctrs.r-lib.org/reference/vec_order Functions to get the order of elements in a vector or to sort a vector. They handle various data types and missing values. ```APIDOC ## vec_order(x, ..., direction = c("asc", "desc"), na_value = c("largest", "smallest")) ### Description Returns an integer vector the same size as `x` representing the permutation required to sort `x`. This is analogous to R's base `order()` function but designed to work with vctrs' type system. ### Parameters - x: A vector. - ...: These dots are for future extensions and must be empty. - direction: Direction to sort in. Defaults to `asc`ending. - na_value: Should `NA`s be treated as the largest or smallest values? Defaults to `largest`. ### Value An integer vector the same size as `x`. ## ## vec_sort(x, ..., direction = c("asc", "desc"), na_value = c("largest", "smallest")) ### Description Sorts a vector according to the specified direction and handling of `NA` values. This function is built upon `vec_order()` and provides a convenient way to obtain a sorted version of a vector. ### Parameters - x: A vector. - ...: These dots are for future extensions and must be empty. - direction: Direction to sort in. Defaults to `asc`ending. - na_value: Should `NA`s be treated as the largest or smallest values? Defaults to `largest`. ### Value A vector with the same size and type as `x`, sorted. ### Examples ```r x <- round(c(runif(9), NA), 3) vec_order(x) #> [1] 3 6 5 9 1 4 7 2 8 10 vec_sort(x) #> [1] 0.122 0.128 0.207 0.374 0.442 0.561 0.753 0.799 0.895 NA vec_sort(x, direction = "desc") #> [1] NA 0.895 0.799 0.753 0.561 0.442 0.374 0.207 0.128 0.122 # Can also handle data frames df <- data.frame(g = sample(2, 10, replace = TRUE), x = x) vec_order(df) #> [1] 5 9 1 4 7 8 10 3 6 2 vec_sort(df) #> g x #> 1 1 0.207 #> 2 1 0.374 #> 3 1 0.442 #> 4 1 0.561 #> 5 1 0.753 #> 6 1 0.895 #> 7 1 NA #> 8 2 0.122 #> 9 2 0.128 #> 10 2 0.799 vec_sort(df, direction = "desc") #> g x #> 1 2 0.799 #> 2 2 0.128 #> 3 2 0.122 #> 4 1 NA #> 5 1 0.895 #> 6 1 0.753 #> 7 1 0.561 #> 8 1 0.442 #> 9 1 0.374 #> 10 1 0.207 # Missing values interpreted as largest values are last when # in increasing order: vec_order(c(1, NA), na_value = "largest", direction = "asc") #> [1] 1 2 vec_order(c(1, NA), na_value = "largest", direction = "desc") #> [1] 2 1 ``` ``` -------------------------------- ### Get unspecified prototype Source: https://vctrs.r-lib.org/reference/vctrs-unspecified Use `vec_ptype()` to obtain the prototype of an unspecified vector. This is useful for understanding how `NA` values are represented before finalisation. ```r vec_ptype(NA) #> [0] vec_ptype(c(NA, NA)) #> [0] ``` -------------------------------- ### Matching expand.grid() Behavior with .vary Source: https://vctrs.r-lib.org/reference/vec_expand_grid Shows how to use the .vary argument to replicate the behavior of base R's expand.grid() by varying the first column fastest. ```r vec_expand_grid(x = 1:2, y = 1:3, .vary = "fastest") #> x y #> 1 1 1 #> 2 2 1 #> 3 1 2 #> 4 2 2 #> 5 1 3 #> 6 2 3 ``` -------------------------------- ### Show Prototype of Unknown Types Source: https://vctrs.r-lib.org/reference/vec_ptype Demonstrates how `vec_ptype_show()` displays the prototype for `NULL` and when no arguments are provided. ```r vec_ptype_show() #> Prototype: NULL vec_ptype_show(NULL) #> Prototype: NULL ``` -------------------------------- ### Custom S3 method for vec_ptype_finalise Source: https://vctrs.r-lib.org/reference/internal-faq-ptype2-identity Provides an example of a custom S3 method for vec_ptype_finalise for the 'ivs_iv' class to handle wrapped vectors. ```R vec_ptype_finalise.ivs_iv <- function(x, ...) { start <- unclass(x)[[1L]] ptype <- vec_ptype_finalise(start, ...) new_bare_iv(ptype, ptype) } ``` -------------------------------- ### Load vctrs and pillar packages Source: https://vctrs.r-lib.org/articles/pillar Load the necessary packages for vector manipulation and pretty printing. ```r library(vctrs) library(pillar) ``` -------------------------------- ### Lossy Cast Error Example Source: https://vctrs.r-lib.org/reference/faq-compatibility-types Illustrates a lossy cast error when attempting to assign a double with fractional values to an integer vector. ```R int_vector <- 1:3 vec_assign(int_vector, 2, 0.001) #> Error in `vec_assign()`: #> ! Can't convert from to due to loss of precision. #> * Locations: 1 ``` -------------------------------- ### Usage of %0% operator Source: https://vctrs.r-lib.org/reference/op-empty-default Demonstrates the basic syntax for using the %0% operator to provide a default value for a vector. ```r x %0% y ``` -------------------------------- ### Common Type Coercion Example Source: https://vctrs.r-lib.org/reference/faq-compatibility-types Shows how integer and logical vectors are combined into a common type (integer) when bound into a data frame. ```R df1 <- data.frame(x = 1:3) df2 <- data.frame(x = FALSE) dplyr::bind_rows(df1, df2) #> x #> 1 1 #> 2 2 #> 3 3 #> 4 0 ``` -------------------------------- ### Unrepresent Repeated Values in a Data Frame Source: https://vctrs.r-lib.org/reference/runs Use `vec_unrep()` on a data frame to get a representation of repeated rows. Runs are constructed rowwise. ```r x <- c("a", "z", "z", "c", "a", "a") y <- c(1, 1, 1, 2, 2, 3) # With multiple columns, the runs are constructed rowwise df <- data_frame( x = x, y = y ) vec_unrep(df) ``` -------------------------------- ### Show Prototype of Matrices Source: https://vctrs.r-lib.org/reference/vec_ptype Demonstrates how `vec_ptype_show()` includes the number of columns in the prototype for matrices. ```r vec_ptype_show(array(1, dim = c(1, 2))) #> Prototype: double[,2] vec_ptype_show(array("x", dim = c(1, 2))) #> Prototype: character[,2] ``` -------------------------------- ### Incompatible Type Error Example Source: https://vctrs.r-lib.org/reference/faq-compatibility-types Demonstrates an incompatible type error when attempting to bind rows of data frames with integer and character columns. ```R df1 <- data.frame(x = 1:3) df2 <- data.frame(x = "foo") dplyr::bind_rows(df1, df2) #> Error in `dplyr::bind_rows()`: #> ! Can't combine `..1$x` and `..2$x` . ``` -------------------------------- ### Get common prototype of multiple vectors Source: https://vctrs.r-lib.org/reference/vec_ptype Use `vec_ptype_common()` to find the common type of multiple vectors. By default, the result is finalized for immediate use. ```r vec_ptype_common(1:3, 1.0:3.0) ``` -------------------------------- ### Get Full Prototype of Factor Source: https://vctrs.r-lib.org/articles/type-size Retrieves the complete prototype object for a factor using `vec_ptype()`, which includes all levels, unlike the summarized output of `vec_ptype_show()`. ```r vec_ptype(factor("a")) #> factor() #> Levels: a ``` -------------------------------- ### Create a list with inferred size Source: https://vctrs.r-lib.org/reference/list_of Shows creating a list where the size of each element is inferred from the input vectors. `.size` is set to `NULL`. ```r library(vctrs) # Create a list with inferred size list_of(c(1, 2), c(3, 4, 5), .size = NULL) ``` -------------------------------- ### Get Run Sizes in a Vector Source: https://vctrs.r-lib.org/reference/runs Use `vec_run_sizes()` to obtain an integer vector representing the size of each run. This is faster than `vec_unrep()` if only run sizes are needed. ```r x <- c("a", "z", "z", "c", "a", "a") vec_run_sizes(x) ``` -------------------------------- ### df_list() Usage Source: https://vctrs.r-lib.org/reference/df_list Illustrates the basic signature of the df_list() function, showing its arguments for constructing data frame components. ```r df_list( ..., .size = NULL, .unpack = TRUE, .name_repair = c("check_unique", "unique", "universal", "minimal", "unique_quiet", "universal_quiet"), .error_call = current_env() ) ``` -------------------------------- ### Initialize a list vector Source: https://vctrs.r-lib.org/reference/vec_init Creates a list vector of size 3, where each element is NULL, based on an empty list template. ```r vec_init(list(), 3) #> [[1]] #> NULL #> #> [[2]] #> NULL #> #> [[3]] #> NULL #> ``` -------------------------------- ### Identify Runs in a Vector Source: https://vctrs.r-lib.org/reference/runs Use `vec_identify_runs()` to get a vector of run identifiers for each element. An attribute `n` is attached, indicating the total number of runs. ```r x <- c("a", "z", "z", "c", "a", "a") vec_identify_runs(x) ``` -------------------------------- ### Show Prototype of Matrices and Arrays Source: https://vctrs.r-lib.org/articles/type-size Demonstrates how `vec_ptype_show()` displays prototypes for matrices and arrays, including their base type and dimensions. ```r vec_ptype_show(array(logical(), c(2, 3))) #> Prototype: logical[,3] vec_ptype_show(array(integer(), c(2, 3, 4))) #> Prototype: integer[,3,4] vec_ptype_show(array(character(), c(2, 3, 4, 5))) #> Prototype: character[,3,4,5] ``` -------------------------------- ### Detect missing values in a vector Source: https://vctrs.r-lib.org/reference/missing Use `vec_detect_missing()` to get a logical vector indicating which elements are missing. Use `vec_any_missing()` to check if any elements are missing. ```r x <- c(1, 2, NA, 4, NA) vec_detect_missing(x) #> [1] FALSE FALSE TRUE FALSE TRUE vec_any_missing(x) #> [1] TRUE ``` -------------------------------- ### Combine data frames using list_combine() Source: https://vctrs.r-lib.org/reference/list_combine Shows that `list_combine()` can also be used to combine data frames. Note that index 2 is not assigned to in this example. ```r x <- list( data.frame(x = 1:2, y = c("a", "b")), data.frame(x = 3:4, y = c("c", "d")) ) indices <- list( c(4, 1), c(3, NA) ) list_combine(x, indices = indices, size = 4) #> x y #> 1 2 b #> 2 NA #> 3 3 c #> 4 1 a ```