Skip to content

Select all columns matching the given indices (or range objects)

Description

Select all columns matching the given indices (or range objects)

Usage

cs__by_index(indices)

Arguments

indices One or more column indices (or ranges). Negative indexing is supported.

Details

Matching columns are returned in the order in which their indexes appear in the selector, not the underlying schema order.

Value

A Polars selector

See Also

cs for the documentation on operators supported by Polars selectors.

Examples

library("polars")

vals <- as.list(0.5 * 0:100)
names(vals) <- paste0("c", 0:100)
df <- pl$DataFrame(!!!vals)
df
#> shape: (1, 101)
#> ┌─────┬─────┬─────┬─────┬───┬──────┬──────┬──────┬──────┐
#> │ c0  ┆ c1  ┆ c2  ┆ c3  ┆ … ┆ c97  ┆ c98  ┆ c99  ┆ c100 │
#> │ --- ┆ --- ┆ --- ┆ --- ┆   ┆ ---  ┆ ---  ┆ ---  ┆ ---  │
#> │ f64 ┆ f64 ┆ f64 ┆ f64 ┆   ┆ f64  ┆ f64  ┆ f64  ┆ f64  │
#> ╞═════╪═════╪═════╪═════╪═══╪══════╪══════╪══════╪══════╡
#> │ 0.0 ┆ 0.5 ┆ 1.0 ┆ 1.5 ┆ … ┆ 48.5 ┆ 49.0 ┆ 49.5 ┆ 50.0 │
#> └─────┴─────┴─────┴─────┴───┴──────┴──────┴──────┴──────┘
# Select columns by index (the two first/last columns):
df$select(cs$by_index(c(0, 1, -2, -1)))
#> shape: (1, 4)
#> ┌─────┬─────┬──────┬──────┐
#> │ c0  ┆ c1  ┆ c99  ┆ c100 │
#> │ --- ┆ --- ┆ ---  ┆ ---  │
#> │ f64 ┆ f64 ┆ f64  ┆ f64  │
#> ╞═════╪═════╪══════╪══════╡
#> │ 0.0 ┆ 0.5 ┆ 49.5 ┆ 50.0 │
#> └─────┴─────┴──────┴──────┘
# Use seq()
df$select(cs$by_index(c(0, seq(1, 101, 20))))
#> shape: (1, 6)
#> ┌─────┬─────┬──────┬──────┬──────┬──────┐
#> │ c0  ┆ c1  ┆ c21  ┆ c41  ┆ c61  ┆ c81  │
#> │ --- ┆ --- ┆ ---  ┆ ---  ┆ ---  ┆ ---  │
#> │ f64 ┆ f64 ┆ f64  ┆ f64  ┆ f64  ┆ f64  │
#> ╞═════╪═════╪══════╪══════╪══════╪══════╡
#> │ 0.0 ┆ 0.5 ┆ 10.5 ┆ 20.5 ┆ 30.5 ┆ 40.5 │
#> └─────┴─────┴──────┴──────┴──────┴──────┘
df$select(cs$by_index(c(0, seq(101, 0, -25))))
#> shape: (1, 5)
#> ┌─────┬──────┬──────┬──────┬─────┐
#> │ c0  ┆ c76  ┆ c51  ┆ c26  ┆ c1  │
#> │ --- ┆ ---  ┆ ---  ┆ ---  ┆ --- │
#> │ f64 ┆ f64  ┆ f64  ┆ f64  ┆ f64 │
#> ╞═════╪══════╪══════╪══════╪═════╡
#> │ 0.0 ┆ 38.0 ┆ 25.5 ┆ 13.0 ┆ 0.5 │
#> └─────┴──────┴──────┴──────┴─────┘
# Select only odd-indexed columns:
df$select(!cs$by_index(seq(0, 100, 2)))
#> shape: (1, 50)
#> ┌─────┬─────┬─────┬─────┬───┬──────┬──────┬──────┬──────┐
#> │ c1  ┆ c3  ┆ c5  ┆ c7  ┆ … ┆ c93  ┆ c95  ┆ c97  ┆ c99  │
#> │ --- ┆ --- ┆ --- ┆ --- ┆   ┆ ---  ┆ ---  ┆ ---  ┆ ---  │
#> │ f64 ┆ f64 ┆ f64 ┆ f64 ┆   ┆ f64  ┆ f64  ┆ f64  ┆ f64  │
#> ╞═════╪═════╪═════╪═════╪═══╪══════╪══════╪══════╪══════╡
#> │ 0.5 ┆ 1.5 ┆ 2.5 ┆ 3.5 ┆ … ┆ 46.5 ┆ 47.5 ┆ 48.5 ┆ 49.5 │
#> └─────┴─────┴─────┴─────┴───┴──────┴──────┴──────┴──────┘