Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

S7 Workaround #1

Open
andrewallenbruce opened this issue Dec 29, 2024 · 0 comments
Open

S7 Workaround #1

andrewallenbruce opened this issue Dec 29, 2024 · 0 comments
Assignees
Labels
question Further information is requested

Comments

@andrewallenbruce
Copy link
Owner

Thanks for the workaround! I was able to apply it to my real use case.

Just for reference to anyone else reading this, here's what you'd do if you still want to rely on referencing an external object (the penguins data frame) to get the property names:

library(S7)
library(rlang)
library(purrr)
library(palmerpenguins)

my_penguin <- as.list(penguins[1,])

penguin <- new_class(
  "penguin",
  properties = list(
    species = class_factor,
    island = class_factor,
    bill_length_mm = class_double,
    bill_depth_mm = class_double,
    flipper_length_mm = class_integer,
    body_mass_g = class_integer,
    sex = class_factor,
    year = class_integer
  ),
  constructor = function(x) {
    props <- set_names(colnames(penguins)) # Get prop names from `penguins` tbl
    prop_vals <- map(props, function(prop_name) pluck(x, prop_name))

    # hack to enable using `new_object()` with NSE.
    constructor <- function() {}
    body(constructor) <- inject(quote(new_object(S7_object(), !!!prop_vals)))
    attributes(constructor) <- attributes(sys.function())
    constructor()
  }
)

penguin(my_penguin)
#> <penguin>
#>  @ species          : Factor w/ 3 levels "Adelie","Chinstrap",..: 1
#>  @ island           : Factor w/ 3 levels "Biscoe","Dream",..: 3
#>  @ bill_length_mm   : num 39.1
#>  @ bill_depth_mm    : num 18.7
#>  @ flipper_length_mm: int 181
#>  @ body_mass_g      : int 3750
#>  @ sex              : Factor w/ 2 levels "female","male": 2
#>  @ year             : int 2007

Created on 2024-11-19 with reprex v2.1.1

Originally posted by @mccarthy-m-g in RConsortium/S7#497 (comment)

@andrewallenbruce andrewallenbruce added the question Further information is requested label Dec 29, 2024
@andrewallenbruce andrewallenbruce self-assigned this Dec 29, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
question Further information is requested
Projects
None yet
Development

No branches or pull requests

1 participant