Skip to content

Instantly share code, notes, and snippets.

@jonocarroll
Last active September 13, 2025 05:33
Show Gist options
  • Save jonocarroll/6d49b7ecca129311c8c84c6158eea698 to your computer and use it in GitHub Desktop.
Save jonocarroll/6d49b7ecca129311c8c84c6158eea698 to your computer and use it in GitHub Desktop.
Using {vec} on a data.frame
library(vec)
x <- as_vec(c(apple = 1, banana = 2, carrot = 3))
is_named <- function(x, y) names(x) %in% y
x[Negate(is_named), "banana"]
#> apple carrot
#> 1 3
m <- as_vec(mtcars)
m[Negate(is_named), c("mpg", "wt")] |>
as.data.frame() |>
head()
#> cyl disp hp drat qsec vs am gear carb
#> Mazda RX4 6 160 110 3.90 16.46 0 1 4 4
#> Mazda RX4 Wag 6 160 110 3.90 17.02 0 1 4 4
#> Datsun 710 4 108 93 3.85 18.61 1 1 4 1
#> Hornet 4 Drive 6 258 110 3.08 19.44 1 0 3 1
#> Hornet Sportabout 8 360 175 3.15 17.02 0 0 3 2
#> Valiant 6 225 105 2.76 20.22 1 0 3 1
library(palmerpenguins)
p <- as_vec(penguins)
p[Negate(is_named), "body_mass_g"] |>
as.data.frame() |>
head()
#> species island bill_length_mm bill_depth_mm flipper_length_mm sex year
#> 1 Adelie Torgersen 39.1 18.7 181 male 2007
#> 2 Adelie Torgersen 39.5 17.4 186 female 2007
#> 3 Adelie Torgersen 40.3 18.0 195 female 2007
#> 4 Adelie Torgersen NA NA NA <NA> 2007
#> 5 Adelie Torgersen 36.7 19.3 193 female 2007
#> 6 Adelie Torgersen 39.3 20.6 190 male 2007
#<sup>Created on 2025-09-13 with [reprex v2.1.1](https://reprex.tidyverse.org)</sup>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment